简体   繁体   中英

C# detect usb device ClassCode (usb device type)

I need to know what kind of USB devices currently used in system. There is a USB specification about class codes of USB devices. But I cant get device type, WMI request WQL: select * from Win32_UsbHub give null values on Class code, Subclass code, Protocol type fields. Any ideas how to detect USB device type currently in use?

My current code:

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
        }
}

You can download USB View Source as a starting point. This loops through all USB devices on a PC (C#) and pulls information about each. To get the Class code , Subclass code , and Protocol type fields, you'll need to modify it slightly. Change the below and run it and you'll get the information on each USB device by clicking on the item in the tree view (information will appear in the right panel).

Modifications to 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; }
}

Modifications to 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"));
   // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM