0

在我的应用程序中,我想在笔式驱动器附加和分离事件上引发事件。我使用以下代码来引发事件。

private ManagementEventWatcher watcherAttach;

private ManagementEventWatcher watcherRemove;        

watcherAttach = new ManagementEventWatcher();
watcherAttach.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcherAttach.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");
watcherAttach.Start();


watcherRemove = new ManagementEventWatcher();
watcherRemove.EventArrived += new EventArrivedEventHandler(watcher_EventRemoved);
watcherRemove.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3");
watcherRemove.Start();


// this are events
void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
     // code to execute
}

void watcher_EventRemoved(object sender, EventArrivedEventArgs e)
{
   //code to execute
}

但问题是这两个事件都引发了两次,并且我的代码在这两个事件中都没有完全执行,有人可以建议我如何克服这个问题吗?

4

1 回答 1

0

我认为最简单的方法是取消订阅一个事件,然后做你的工作并再次订阅。当您取消订阅时,插入其他设备的可能性很小。在处理键盘上的双击键时,我也是这样做的。

// this are events
void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
watcherAttach.EventArrived -= new EventArrivedEventHandler(watcher_EventArrived);
     // code to execute
watcherAttach.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
}

void watcher_EventRemoved(object sender, EventArrivedEventArgs e)
{
watcherRemove.EventArrived -= new EventArrivedEventHandler(watcher_EventRemoved);
   //code to execute
watcherRemove.EventArrived += new EventArrivedEventHandler(watcher_EventRemoved);
}
于 2012-12-24T12:07:06.733 回答