如何列举所有HID装置?c#
本文关键字:装置 HID 何列举 | 更新日期: 2023-09-27 18:16:21
我需要枚举连接到我的PC的所有HID设备。我试图使用这个答案,但它列举了USBHub设备,我找不到我的HID设备。
编辑:我很想知道是否有任何WIN32 API方法,使用PID和VID获得USB设备状态(在线/离线)?
我找到了答案。这个链接解释了如何使用ManagementObjectSearcher
完成此操作。
感谢所有回复的人!
微软的WDK有关于HID函数的文档和如何使用它们的概述。WDK还包括与访问hid类设备的Visual c++程序一起使用的头文件(hidsdi.h, hidusage.h, hidpi.h)。
查看此链接Jan Axelson的Lakeview Research - HID Windows Programming。
这是一个关于你在问题中指定的HID设备的问题:使用c#扫描人机界面设备(HID)
您可以像这样枚举带有Windows api的Hid设备:
public static Collection<DeviceInformation> GetConnectedDeviceInformations()
{
var deviceInformations = new Collection<DeviceInformation>();
var spDeviceInterfaceData = new SpDeviceInterfaceData();
var spDeviceInfoData = new SpDeviceInfoData();
var spDeviceInterfaceDetailData = new SpDeviceInterfaceDetailData();
spDeviceInterfaceData.CbSize = (uint)Marshal.SizeOf(spDeviceInterfaceData);
spDeviceInfoData.CbSize = (uint)Marshal.SizeOf(spDeviceInfoData);
var hidGuid = new Guid();
APICalls.HidD_GetHidGuid(ref hidGuid);
var i = APICalls.SetupDiGetClassDevs(ref hidGuid, IntPtr.Zero, IntPtr.Zero, APICalls.DigcfDeviceinterface | APICalls.DigcfPresent);
if (IntPtr.Size == 8)
{
spDeviceInterfaceDetailData.CbSize = 8;
}
else
{
spDeviceInterfaceDetailData.CbSize = 4 + Marshal.SystemDefaultCharSize;
}
var x = -1;
while (true)
{
x++;
var setupDiEnumDeviceInterfacesResult = APICalls.SetupDiEnumDeviceInterfaces(i, IntPtr.Zero, ref hidGuid, (uint)x, ref spDeviceInterfaceData);
var errorNumber = Marshal.GetLastWin32Error();
//TODO: deal with error numbers. Give a meaningful error message
if (setupDiEnumDeviceInterfacesResult == false)
{
break;
}
APICalls.SetupDiGetDeviceInterfaceDetail(i, ref spDeviceInterfaceData, ref spDeviceInterfaceDetailData, 256, out _, ref spDeviceInfoData);
var deviceInformation = GetDeviceInformation(spDeviceInterfaceDetailData.DevicePath);
if (deviceInformation == null)
{
continue;
}
deviceInformations.Add(deviceInformation);
}
APICalls.SetupDiDestroyDeviceInfoList(i);
return deviceInformations;
}
全类:https://github.com/MelbourneDeveloper/Hid.Net/blob/master/Hid.Net/Windows/WindowsHIDDevice.cs
api: https://github.com/MelbourneDeveloper/Hid.Net/blob/master/Hid.Net/Windows/APICalls.cs