0

我正在使用 WMI 查找插入 USB 设备的事件。我创建了一个独立类来尝试这个,效果很好!一旦我从我的应用程序中调用该类,它就不起作用。代码是相同的,除了当我将类编译为独立 exe 时的 main() 。代码如下:

 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();

DeviceChangeEventReceived 方法在内置到较大的应用程序中时永远不会被调用。我认为这可能是范围,但似乎不是。我确信这很简单,但我没有想法。谢谢!

4

1 回答 1

1

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.

于 2013-10-02T21:02:57.083 回答