WMI: Get USB device description on insertion
Asked Answered
L

1

6

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?

Lynnelynnea answered 10/7, 2011 at 17:27 Comment(0)
L
15

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)

Lugworm answered 10/7, 2011 at 18:59 Comment(2)
perhaps you may select my response as helpful and set it to "answered" :D thx in advanceLugworm
why the downvote? pls let me know what you did not like? what is wrong in your opinion?Lugworm

© 2022 - 2024 — McMap. All rights reserved.