Reputation: 692
I am using WMI to find events where a USB device is plugged in. I made a standalone class to try this out, and it worked great! As soon as I call the class from my application, it does not work. The code is identical, with the exception of the main() when I compile the class as a stand-alone exe. The code follows:
ManagementScope scope = new ManagementScope("root\\CIMV2"); //set the scope
WqlEventQuery query = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WHERE TargetInstance ISA 'Win32_PnPEntity'"); //set the events
watcher = new ManagementEventWatcher(scope, query);
watcher.EventArrived += new EventArrivedEventHandler(this.DeviceChangeEventReceived);
watcher.Start();
The DeviceChangeEventReceived method is never called when built into the larger application. I thought it might be the scope, but it seems not to be. I am sure that it's something simple, but I'm out of ideas. Thanks!
Upvotes: 0
Views: 201
Reputation: 692
I have determined that there exists a need for a modified WMI query between the stand-alone class and the application that calls the class. There needs to be a TIMESPAN present. I found this just by dumb luck where I gave the handler a timespan of 10s and it worked!
"SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE TargetInstance ISA 'Win32_PnPEntity'"
It seems that the WQLEventQuery method just polls if a timespan is not specified, and in this case, it causes things to be nasty. It would have been nice if it threw an exception, but something is probably getting buried in InterloperServices.
Upvotes: 1