private static extern Boolean HidD_GetAttributes(IntPtr hidHandle, out HID_ATTRIBUTES attributes);
private int HIDSearch(int max_try) { HIDInfoList.Clear(); //指定HID类的GUID Guid guidHID = Guid.Empty; HidD_GetHidGuid(ref guidHID); //获取GUID类型设备信息指针 hDevInfo IntPtr hDevInfo = IntPtr.Zero; hDevInfo = SetupDiGetClassDevs(ref guidHID, 0, IntPtr.Zero, DIGCF.DIGCF_PRESENT | DIGCF.DIGCF_DEVICEINTERFACE); ////设备信息数据 devInfoData SP_DEVICE_INTERFACE_DATA DeviceInterfaceData = new SP_DEVICE_INTERFACE_DATA(); DeviceInterfaceData.cbSize = (UInt32)Marshal.SizeOf(DeviceInterfaceData); SP_DEVINFO_DATA strtInterfaceData = new SP_DEVINFO_DATA(); strtInterfaceData.cbSize = (UInt32)Marshal.SizeOf(strtInterfaceData); SP_DEVICE_INTERFACE_DETAIL_DATA detailData = new SP_DEVICE_INTERFACE_DETAIL_DATA(); detailData.cbSize = (UInt32)Marshal.SizeOf(detailData); //循环内所需数据 int device_found = 0; UInt32 device_index = 0; int device_max_try = max_try; int bufferSize = 0; IntPtr hidHandle = IntPtr.Zero; while (device_max_try > 0) { device_max_try--; if (SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guidHID, device_index, ref DeviceInterfaceData)) { SetupDiGetDeviceInterfaceDetail(hDevInfo, ref DeviceInterfaceData, IntPtr.Zero, 0, ref bufferSize, strtInterfaceData); IntPtr detailDataBuffer = Marshal.AllocHGlobal(bufferSize); Marshal.StructureToPtr(detailData, detailDataBuffer, false); if (SetupDiGetDeviceInterfaceDetail(hDevInfo, ref DeviceInterfaceData, detailDataBuffer, bufferSize, ref bufferSize, strtInterfaceData)) { string devicePathName = Marshal.PtrToStringAuto(detailDataBuffer + sizeof(UInt32)); hidHandle = CreateFile(devicePathName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); if (hidHandle != IntPtr.Zero && hidHandle.ToInt32() != -1) { HID_ATTRIBUTES hidAttributes = new HID_ATTRIBUTES(); HidD_GetAttributes(hidHandle, out hidAttributes); byte[] pname = new byte[NAME_LENS]; HidD_GetProductString(hidHandle, pname, NAME_LENS); byte[] vname = new byte[NAME_LENS]; HidD_GetManufacturerString(hidHandle, vname, NAME_LENS); string str_pname = Encoding.Default.GetString(pname); string str_vname = Encoding.Default.GetString(vname); HIDINFO hidInfo = new HIDINFO(); hidInfo.handle = hidHandle; hidInfo.path = devicePathName; hidInfo.pid = hidAttributes.ProductID; hidInfo.vid = hidAttributes.VendorID; hidInfo.pname = str_pname.Replace("\0", ""); hidInfo.vname = str_vname.Replace("\0", ""); HIDInfoList.Add(hidInfo); device_found++; } } } device_index++; } return(device_found); }