C# 访问USB(HID)设备方法 (转)

依次使用一下函数:

1、static public extern void HidD_GetHidGuid (ref System.Guid HidGuid);

      获取HID的全局GUID

2、static public extern IntPtr SetupDiGetClassDevs(ref System.Guid ClassGuid,

    string Enumerator,

    int hwndParent,

    int Flags);

      获取所有hid句柄

3、static public extern int SetupDiEnumDeviceInterfaces(IntPtr DeviceInfoSet,

    int DeviceInfoData,

    ref System.Guid InterfaceClassGuid,

    int MemberIndex,

    ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData);

  检测集合每个接口,成功返回true

4、 static public extern bool SetupDiGetDeviceInterfaceDetail(IntPtr DeviceInfoSet,

    ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData,

    IntPtr DeviceInterfaceDetailData,

    int DeviceInterfaceDetailDataSize,

    ref int RequiredSize,

    IntPtr DeviceInfoData);

  获取接口信息,第一次失败 但可获得信息缓冲区大小

5、 static public extern bool SetupDiGetDeviceInterfaceDetail(IntPtr DeviceInfoSet,

    ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData,

    IntPtr DeviceInterfaceDetailData,

    int DeviceInterfaceDetailDataSize,

    ref int RequiredSize,

    IntPtr DeviceInfoData);

  第二次获取

循环 3、4、5把所有的设备读取,把所有设备路径名存放在一个数组里devicePathName

6、 CreateFile(string lpFileName,

    uint dwDesiredAccess,

    uint dwShareMode,

    ref SECURITY_ATTRIBUTES lpSecurityAttributes,

    int dwCreationDisposition,

    uint dwFlagsAndAttributes,

    int hTemplateFile);

  根据devicePathName链接文件

以上步骤成功就可以读写USB了

原文地址:https://www.cnblogs.com/gr816/p/7903796.html