Opening my application when a usb device is inserted on Windows using WMI

Posted by rsteckly on Stack Overflow See other posts from Stack Overflow or by rsteckly
Published on 2010-05-14T20:20:45Z Indexed on 2010/05/14 20:24 UTC
Read the original article Hit count: 254

Filed under:
|

Hi,

I'm trying to launch an event when someone plugs in a usb device. For now, I'm content to simply print something to the console (in the finished product, it will launch an application).

This code is very loosely adapted from: http://serverfault.com/questions/115496/use-wmi-to-detect-a-usb-drive-was-connected-regardless-of-whether-it-was-mounted

There's two problems: 1) I need to pass the argument to Management scope dynamically because this will be installed on computers I don't use or whose name I don't know. 2) I'm getting an invalid namespace exception when I call w.Start();

Any ideas what I'm doing wrong?

static ManagementEventWatcher w=null;
    static void Main(string[] args)
            {
                AddInstUSBHandler();
                for(;;);


            }



    public static void USBRemoved(object sneder, EventArgs e)
            {
                Console.WriteLine("A USB device inserted");
            } 





 static void AddInstUSBHandler()
            {
                WqlEventQuery q;
                ManagementScope scope = new ManagementScope("HQ\\DEV1");
                scope.Options.EnablePrivileges=true;

                    q=new WqlEventQuery();
                    q.EventClassName+="_InstanceCreationEvent";
                    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();           
            }

© Stack Overflow or respective owner

Related posts about .NET

Related posts about wmi