How to prevent specific keyboard inputing into TextBox in WPF

Viewed 240

I have a system with two HID keyboards (actually, one's a barcode scanner.). I Register the device('barcode scanner') for reading raw input data.

I set the RIDEV_NOLEGACY | RIDEV_INPUTSINK to the dwFlags of the RAWINPUTDEVICE. Then I can read and process raw input data in my code.

But, because I set the RIDEV_NOLEGACY dwFlags, another generial keyboard cannot input anything into the TextBox on XAML. That's not what I want. I just want to prevent the barcode scanner from entering directly into the text box, instead of all keyboards.

The following is the code sample(you need to install the nuget package 'sharplibhid'):

private SharpLib.Hid.Handler iHidHandler;
    
    private void Window1_Loaded(object sender, RoutedEventArgs e)
    {
        HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
        source.AddHook(WndProc);

        RAWINPUTDEVICE[] rid = new RAWINPUTDEVICE[1];
        rid[0].usUsagePage = 0x01;

        rid[0].usUsage = 0x06;

        rid[0].dwFlags = RawInputDeviceFlags.RIDEV_INPUTSINK | RawInputDeviceFlags.RIDEV_NOLEGACY;

        rid[0].hwndTarget = source.Handle;

        iHidHandler = new SharpLib.Hid.Handler(rid);

        iHidHandler.OnHidEvent += HandleHidEventThreadSafe;
    }

    public void HandleHidEventThreadSafe(object aSender, SharpLib.Hid.Event aHidEvent)
    {
        if (aHidEvent.IsStray)
        {
            //Stray event just ignore it
            return;
        }
        else
        {
            // do something...
            if (aHidEvent.Device.ProductId == xxx && aHidEvent.Device.VendorId == xxx)
            {
                Debug.WriteLine(aHidEvent.VirtualKey.ToString());
            }
        }
    }

    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        Message message = Message.Create(hwnd, msg, wParam, lParam);

        switch (msg)
        {
            case Const.WM_INPUT:

                iHidHandler.ProcessInput(ref message);
                handled = true;
                break;
        }

        return IntPtr.Zero;
    }
1 Answers

I suggest using simple textBox to read all kinds of keyboards and in barcode reader device active to pass Enter after decoding the barcode So you can read both of them keyboard and barcode reader data.

Related