Opening my application when a USB device is inserted on Windows using WMI
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: https://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();
}
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");
精彩评论