WMI: Get USB device description on insertion

我的梦境 提交于 2019-11-28 00:47:21

问题


How can I get a device Id and other description on insertion of USB device? I've found an example how to get notified about USB device insertion/removal. But how to get device desrtiption info?

Here is my code snippet:

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()....

UPDATE: Actually, it is a Serial COM device with USB connection. So there is no driveName property. How can I get USB description, which I can see in Device Manager? Does WMI provide this info with the notification about USB insertion?


回答1:


Complete new answer according to your updated answer. You may check für any connected USB device:

        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());
        }

(see MSDN WMI tasks examples) for this)

or have a look into any 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());
        }

(see ActiveX Experts for further details on this)



来源:https://stackoverflow.com/questions/6642633/wmi-get-usb-device-description-on-insertion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!