C# 检测 USB 设备的 ClassCode (USB 设备类型)。

9

我需要知道当前系统中使用了哪种类型的USB设备。关于USB设备的类别码,有一个USB规范。但是我无法获取设备类型,WMI请求 WQL: select * from Win32_UsbHub 在类别码、子类别码、协议类型字段上返回空值。您有什么想法可以检测当前正在使用的USB设备类型吗?

我目前的代码:

ManagementObjectCollection collection; 
using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub")) 
{
    collection = searcher.Get();
    foreach (var device in collection)
        {
            var deviceId = (string)GetPropertyValue("DeviceID");
            var pnpDeviceId = (string)GetPropertyValue("PNPDeviceID");
            var descr = (string)device.GetPropertyValue("Description");
            var classCode = device.GetPropertyValue("ClassCode"); //null here
        }
}

wbemtest.exe 工具产生相同的效果:Class cod, Subclass code, Protocol type 字段为空。 - MelnikovI
1
根据您提供的USB规范,您需要深入了解设备描述符(设备类)或接口描述符(接口类)以检索该信息。您可能无法仅使用WMI完成此操作。 - SwDevMan81
你在寻找什么类型的设备?如果你正在寻找特定类型的设备(比如虚拟串口),最好查看专门针对这些项目的wmi查询。 - Rich Dominelli
@SwDevMan81 我该如何在C#中检索设备描述符(设备类)或接口描述符(接口类)? - MelnikovI
@MelnikovI - 我已经发布了一个检索信息的解决方案。如果您对此有任何疑问或问题,请告诉我。 - SwDevMan81
显示剩余2条评论
1个回答

5
您可以下载USB View Source作为起点。该源码以 C# 语言循环遍历PC上的所有USB设备,并提取每个设备的信息。要获取类别代码,子类别代码和协议类型字段,请稍作修改。更改下面的内容并运行它,然后通过单击树视图中的项目来获得每个USB设备的信息(信息将显示在右侧面板)。 对 USB.cs 的修改:
// Add the following properties to the USBDevice class
// Leave everything else as is
public byte DeviceClass
{
   get { return DeviceDescriptor.bDeviceClass; }
}

public byte DeviceSubClass
{
   get { return DeviceDescriptor.bDeviceSubClass; }
}

public byte DeviceProtocol
{
   get { return DeviceDescriptor.bDeviceProtocol; }
}

修改 fmMain.cs

// Add the following lines inside the ProcessHub function
// inside the "if (port.IsDeviceConnected)" statement
// Leave everything else as is
if (port.IsDeviceConnected)
{
   // ...
   sb.AppendLine("SerialNumber=" + device.SerialNumber);
   // Add these three lines
   sb.AppendLine("DeviceClass=0x" + device.DeviceClass.ToString("X"));
   sb.AppendLine("DeviceSubClass=0x" + device.DeviceSubClass.ToString("X"));
   sb.AppendLine("DeviceProtocol=0x" + device.DeviceProtocol.ToString("X"));
   // ...
}

@PeterJ - 看起来文件结构有所改变,我已更新链接。 - SwDevMan81

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接