tags:

views:

44

answers:

1

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 are 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();
    }
+1  A: 

This line is incorrect -> "HQ\DEV1"

//ManagementScope scope = new ManagementScope("HQ\\DEV1");

Follow ManagementScope Class

    // Make a connection to a remote computer.
    // Replace the "FullComputerName" section of the
    // string "\\\\FullComputerName\\root\\cimv2" with
    // the full computer name or IP address of the
    // remote computer.
    ManagementScope scope = 
        new ManagementScope(
        "\\\\FullComputerName\\root\\cimv2");
volody
I added the full computer name--and then got "invalid class". If I change it to \\\\HQ\\DEV1\\root\\cimv2, (which isn't the full computer name but the path in the domain) I get "access is denied." Would that be because I'm not the administrator on my box?
rsteckly