Processing a USB barcode scanner that acts like a keyboard with a header / trailers from anywhere in the form

In the winforms application, I need to read input from a standard USB barcode scanner, which makes it like a USB keyboard for Windows. This should work without focusing on a specific control (i.e. I canโ€™t say โ€œclick on this text box and then scan the barcodeโ€). The scanner is configured to display the header and trailer for all codes that it scans.

I would prefer not to go in a "raw" way, i.e. directly connect to USB input or Windows events (WM_INPUT and the like).

I can, of course, mask the keystrokes in ProcessCmdKey, but then I seem to be unable to correctly identify the keys for the header / trailer (^ ~ {and} ~ ^ respectively).

Any idea how this can be done correctly in managed code?

0
source share
3 answers

This works, but it is 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); } 
+3
source

ProcessCmdKey is the right place for this.

0
source

perhaps a text field hidden by the panel that receives focus when the barcode should be scanned, and then use the keydown event, which should receive the raw values โ€‹โ€‹of the ascii characters sent by the scanner

0
source

Source: https://habr.com/ru/post/1341366/


All Articles