Search code examples
c#wpfinputioascii

WPF detect ASCII prefix of barcode scanner in previewKeyDown


I have a 2D Barcode Scanner configured as an HID input device (acts as a normal keyboard). My plan was to differentiate between user keyboard input and barcode-scanner input by looking for the prefix and suffix that the barcode scanner can add to the scanned characters.

I have currently configured the barcode scanner to use ASCII 0x02 (Start of Text) as the prefix and 0x03 (End of Text) as the suffix.

How can I detect these special ASCII inputs in C#? I am using an KeyEventHandler to detect key inputs on PreviewKeyDown as well as PreviewKeyUp.

I've tried:

public MainWindow()
{
    this.PreviewKeyDown += new KeyEventHandler(PreviewKeyDownEventBarcodeScanner);
    this.PreviewKeyUp += new KeyEventHandler(PreviewKeyUpEventBarcodeScanner);
}

private void PreviewKeyDownEventBarcodeScanner(object sender, KeyEventArgs e) {
    int vkey = (int)KeyInterop.VirtualKeyFromKey(e.Key);
    stringOfVKeyInputs += vkey.ToString() + " ";
    stringOfKeyToTextInputs += e.Key.ToString();
}

Unfortunately none of the 2 variants (saved in the 2 strings) really helped to detect the special inputs.

  • e.Key.ToString() always just outputs "System" for the 0x02 or 0x03 inputs.
  • KeyInterop.VirtualKeyFromKey(e.Key) gives 0x00 0x00 as an output for an ASCII 0x02 input; and 0x00 0x00 0xD as an output for an ASCII 0x03 input (which is bad because 0xD is VKEY_RETURN).

Is there any way to get the actual ASCII code of the input?


Solution

  • If you receive Key.System, check e.SystemKey

    int vkey = KeyInterop.VirtualKeyFromKey(e.Key == Key.System ? e.SystemKey : e.Key);