雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

使用C#读取USB HID设备的代码示例

2024-06-19 37

在C#中,读取USB设备通常涉及到使用Windows的API,如SetupAPI和HidAPI。以下是一个基于HidAPI的示例,用于读取USB HID设备:

using System;
using HidLibrary;

class Program
{
    static void Main(string[] args)
    {
        HidDevices.Enumerate(OnDeviceFound);

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    private static void OnDeviceFound(HidDevice device)
    {
        Console.WriteLine($"Found a HID device with VendorID: {device.VendorId} and ProductID: {device.ProductId}");
        
        if (device.IsOpen)
        {
            device.Close();
        }

        device.OpenDevice();

        byte[] readBuffer = new byte;

        while (device.IsOpen)
        {
            int bytesRead = device.Read(readBuffer, readBuffer.Length, 1000);

            if (bytesRead > 0)
            {
                Console.WriteLine($"Read {bytesRead} bytes from the device.");

                // Process the read buffer here...

            }
        }

        device.CloseDevice();
    }
}

在这个示例中,我们首先调用HidDevices.Enumerate方法来枚举所有可用的USB HID设备。对于每个找到的设备,我们注册一个回调函数OnDeviceFound。在这个回调函数中,我们检查设备是否已经打开,如果是,我们先关闭它,然后打开设备以便进行读写操作。

我们创建了一个字节数组readBuffer作为接收数据的缓冲区,然后进入一个循环,不断地尝试从设备中读取数据。Read方法会返回实际读取到的字节数,如果读取到数据,我们就将其输出到控制台。

这个示例仅用于演示如何使用HidAPI在C#中读取USB HID设备。在实际应用中,你需要根据你的具体需求来处理接收到的数据,并且可能需要处理各种错误情况和异常。此外,对于非HID类的USB设备,你可能需要使用其他API,如SetupAPI。

更新于:3个月前
赞一波!

文章评论

全部评论