处理充当键盘的USB条码扫描器,并在表格上的任何位置使用标头/预告片 [英] Handling USB Barcode Scanner acting as a keyboard, with header/trailers from anywhere on the form
问题描述
在winforms应用程序中,我需要从标准的USB条码扫描器读取输入,该扫描器使iteself像Windows的USB键盘一样显示.这必须在不将焦点放在特定控件上的情况下进行(即,我不能说单击此文本框然后扫描条形码").扫描程序配置为向扫描的每个代码输出标题和结尾.
In a winforms app, I need to read input from a standard USB barcode scanner, one which makes iteself appears as a USB keyboard to windows. This has to work without giving focus to a particular control (ie, I can't say "click on this textbox then scan the barcode"). The scanner is configured to output a header and trailer to every codes it scans.
我宁愿不采用原始"方式,即直接挂接到USB输入或Windows事件(WM_INPUT等).
I'd rather don't go the "raw" way, ie, hooking directly into the USB input or Windows events (WM_INPUT and such).
我当然可以将键击捕获在ProcessCmdKey中,但是随后我似乎无法正确识别页眉/尾部的键(分别为^〜{和}〜^).
I can of course trap the keystrokes in ProcessCmdKey, but then I don't seem to be able to properly identify the keys for the header/trailer (^~{ and }~^ respectively).
您知道如何在托管代码中正确完成此操作吗?
Any idea how this can be done properly in managed code?
推荐答案
这可行,但是有点难看:
This works, but it's kinda ugly:
[DllImportAttribute("User32.dll")]
public static extern int ToAscii(int uVirtKey, int uScanCode, byte[] lpbKeyState, byte[] lpChar, int uFlags);
[DllImportAttribute("User32.dll")]
public static extern int GetKeyboardState(byte[] pbKeyState);
public static char GetAsciiCharacter(int uVirtKey, int uScanCode)
{
byte[] lpKeyState = new byte[256];
GetKeyboardState(lpKeyState);
byte[] lpChar = new byte[2];
if (ToAscii(uVirtKey, uScanCode, lpKeyState, lpChar, 0) == 1)
return (char)lpChar[0];
else
return new char();
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if(keyData == Keys.ShiftKey || keyData == Keys.Shift)
return base.ProcessCmdKey(ref msg, keyData);
char keyChar = GetAsciiCharacter((int) (keyData & Keys.KeyCode), (((int) msg.LParam) & 0x1000000));
if(keyChar == '\0')
return base.ProcessCmdKey(ref msg, keyData);
_currentSequence.Add(keyChar);
if (_currentSequence.ToString() == "^~{")
{
_handlingInputFromScanner = true;
_scannerBuffer.Clear();
return true;
}
if (_currentSequence.ToString() == "}~^")
{
_handlingInputFromScanner = false;
OnScannerRead.Invoke(this, new ScannerReadEventArgs { ScannerData = _scannerBuffer.ToString() });
_scannerBuffer.Clear();
return true;
}
if (keyChar == '}' || keyChar == '{' || keyChar == '~' || keyChar == '^')
{
return true;
}
if (_handlingInputFromScanner)
{
_scannerBuffer.Append(keyChar);
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
这篇关于处理充当键盘的USB条码扫描器,并在表格上的任何位置使用标头/预告片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!