WMI:插入时获取USB设备描述

时间:2011-07-10 17:27:41

标签: c# .net wmi insertion usb

如何在插入USB设备时获取设备ID和其他说明? 我找到了一个如何获得USB设备插入/删除通知的示例。但是如何获得设备解析信息?

这是我的代码段:

WqlEventQuery q;
ManagementScope scope = new ManagementScope("root\\CIMV2");
scope.Options.EnablePrivileges = true;

try
{
    q = new WqlEventQuery();
    q.EventClassName = "__InstanceDeletionEvent";
    q.WithinInterval = new TimeSpan(0, 0, 3);
    q.Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'";
    w = new ManagementEventWatcher(scope, q);
    w.EventArrived += new EventArrivedEventHandler(USBRemoved);
    w.Start();
}
... catch()....

更新:实际上,它是一个带USB连接的串行COM设备。所以没有driveName属性。如何获取USB描述,我可以在设备管理器中看到? WMI是否提供有关USB插入的通知的信息?

1 个答案:

答案 0 :(得分:15)

根据您更新的答案

完成新答案。您可以查看任何连接的USB设备

        ManagementScope sc =
            new ManagementScope(@"\\YOURCOMPUTERNAME\root\cimv2");

        ObjectQuery query =
            new ObjectQuery("Select * from Win32_USBHub");

        ManagementObjectSearcher searcher = new ManagementObjectSearcher(sc, query);
        ManagementObjectCollection result = searcher.Get();

        foreach (ManagementObject obj in result)
        {
            if (obj["Description"] != null) Console.WriteLine("Description:\t" + obj["Description"].ToString());
            if (obj["DeviceID"] != null) Console.WriteLine("DeviceID:\t" + obj["DeviceID"].ToString());
            if (obj["PNPDeviceID"] != null) Console.WriteLine("PNPDeviceID:\t" + obj["PNPDeviceID"].ToString());
        }

(参见MSDN WMI tasks examples))

或查看任何 COM ConnectedDevice

        ManagementScope sc =
            new ManagementScope(@"\\YOURCOMPUTERNAME\root\cimv2");
        ObjectQuery query =
            new ObjectQuery("Select * from Win32_SerialPort");

        searcher = new ManagementObjectSearcher(sc, query);
        result = searcher.Get();

        foreach (ManagementObject obj in result)
        {
            if (obj["Caption"] != null) Console.WriteLine("Caption:\t" + obj["Description"].ToString());
            if (obj["Description"] != null) Console.WriteLine("Description:\t" + obj["DeviceID"].ToString());
            if (obj["DeviceID"] != null) Console.WriteLine("DeviceID:\t" + obj["PNPDeviceID"].ToString());
        }

(有关详细信息,请参阅ActiveX Experts