Detecting input from any USB HID in C# using HidLi

2019-06-24 13:17发布

First of all i am new to C#. I want to create an application that detects any usb hid device (I have used HidLibrary and it detects the HIDs) but i want to get input from the hid as well (I have used Raw input but that doesn't work i think its only for keyboards). for example if i have connected a mouse then any type of input from that mouse either movement or clicks will cause a function to run.

All i want to know is that which function is executed in the HidLibrary when an input comes from the HID? Or if there is a better alternative than HidLibrary. If you can provide any code snippet i ll be very thankful :)

标签: c# usb hid
1条回答
Deceive 欺骗
2楼-- · 2019-06-24 13:30

HidLibrary is pretty good compared with the others I've used so try stick with it.

When Data comes in it fires the "OnReport" handler that you assign when initialising your HidDevice.

E.g.

_myDevice = HidDevices.Enumerate(myVendorId, myProductId).FirstOrDefault();

if (_myDevice != null)
{
    _myDevice.OpenDevice();

    _myDevice.Inserted += DeviceAttachedHandler;
    _myDevice.Removed += DeviceRemovedHandler;

    _myDevice.MonitorDeviceEvents = true;

    // this is where we start listening for data
    _myDevice.ReadReport(OnReport); 
}

In this case, "OnReport" is the name of your event handler and it will be called when whenever data arrives from your device. The name "OnReport" isn't very descriptive, but the examples all use this name so I've stuck with it in my code as well. What's important is that at the end of the handler, you ask your device to fire back again after more data arrives, hence the last line in the OnReport function calling again to ReadReport.

private void OnReport(HidReport report)
{
    if (attached == false) { return; }

    // process your data here
    var byteFromMyDevice = report.Data[0];

    // we need to start listening again for more data
    _myDevice.ReadReport(OnReport);
}
查看更多
登录 后发表回答