在我的应用程序中,我想在笔式驱动器附加和分离事件上引发事件。 我使用以下代码来举起活动。
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
}
但问题是这两个事件都被提升了两次并且我的代码在两个事件中都没有完全执行,任何人都可以建议我如何克服这个事件?
答案 0 :(得分: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);
}