determine if a specific USB device is plugged in

S

Steve

I want to check if a USB device is availble on a system. Is this possible?
I see it in the Device Manager, so I think it must be possible "somehow" :)
 
R

reviswami78

You don't need to go to all those unmanaged API's. The .NET WMI
wrappers provides clean access to system devices.

Here is a code snippet that will let you determine if a usb device is
plugged in. Your code will change slightly depending on what type (i.e.
CLASS) the usb device is. In any case to be alerted when a usb device
is plugged in, you can use a WQL (Windows Query Language) query, and
register a handler, as follows:

using System.Management;
.....

//create a query to look for usb devices
WqlEventQuery w = new WqlEventQuery();
w.EventClassName = "__InstanceCreationEvent";
w.Condition = "TargetInstance ISA 'Win32_USBControllerDevice'";
w.WithinInterval = new TimeSpan(0,0,2);

//use a "watcher", to run the query
ManagementEventWatcher watch = new ManagementEventWatcher(w);
watch.EventArrived+= new
EventArrivedEventHandler(this.usbDetectionHandler);
watch.Start();

//when the watcher detects the query is true, it calls the registered
handler
//in this case usb.DetectionHandler


Hope this helps. If you have follow up queries do let me know.

Revi
 
S

Steve

Great, this is very cool!
Currently I'm getting a list of all devices and doing a string search to
determine if the one that I'm interested in is present, then I check it's
state and error code. But I only do this at startup and was wondering how I
would handle someone REMOVING the device... now I know, thank you!

-Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top