Search code examples
c#.netusb.net-6.0hid

Read HID device input, e.g. from a keyboard or barcode scanner


So I know this question has been asked many times, but I cannot seem to find a proper answer.

Does anyone know how to read from a HID device from any C#/.NET (.NET 6) application?

I've tried several packages/projects, such as:

These projects are focussed on fetching data from all keyboards and checking where the data came from.

Now what I'm really looking for is a library/way to receive data from these devices without needing a windows forms handle or even focus to the application. It should work in such a way that I can simply get the data from the device without requiring any user interaction or focus on the application, so that it would work from a .NET console application.

One really interesting library I found is the HID.NET library (https://github.com/MelbourneDeveloper/Device.Net), one of the issues with this library is that I get the same issue as this guy (https://github.com/MelbourneDeveloper/Device.Net/issues/88). So it states that access is denied to open the device for reading.

This means I cannot use this library either.

Therefore I felt like maybe someone on here could help me further. I would like any direction in which I could go to get further with this issue.

Many thanks in advance.


Solution

  • Very curiously, Microsoft chose to open these sort of devices in so called "Exclusive mode", see: https://learn.microsoft.com/en-us/windows-hardware/drivers/hid/hid-architecture#hid-clients-supported-in-windows

    This states that these devices are opened in Exclusive mode:

    • Mouse class driver and mapper driver
    • Keyboard / Keypad class driver and mapper driver
    • External Pen Device
    • Integrated Pen Device
    • Touchscreen
    • Precision Touchpad (PTP)

    About this exclusive mode, they state the following:

    In the preceding table, the access mode for input HID clients is Exclusive to prevent other HID clients from intercepting or receiving global input state when they are not the target recipient of that input. Therefore, for security reasons RIM (Raw Input Manager) opens all such devices exclusively.

    If device is opened in Exclusive mode by RIM (Raw Input Manager) user can still open HID device interface without requesting read and write permissions and obtain HID device information via HIDClass support routines (HidD_GetXxx).

    This means that what I'm trying to do, so receive the USB-HID packages shall never(?) be allowed and is therefore not an option. In order to achieve such functionality as I desire, switching drivers to custom HID or COMport can be an option.