0

I tried to catch the event when a portable device is inserted and was able to do so. My problem is that it called two events of the insertion.

Here is my code:

 private void DeviceInsertedEvent(object sender, EventArrivedEventArgs e)
    {
            MessageBox.Show("Device Received");
    }

private void DeviceRemovedEvent(object sender, EventArrivedEventArgs e)
{
        MessageBox.Show("Device Removed");
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    WqlEventQuery insertQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 3 WHERE TargetInstance ISA 'Win32_PnPEntity'");
    ManagementEventWatcher insertWatcher = new ManagementEventWatcher(insertQuery);
    insertWatcher.EventArrived += new EventArrivedEventHandler(DeviceInsertedEvent);
    insertWatcher.Start();

    WqlEventQuery removeQuery = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 3 WHERE TargetInstance ISA 'Win32_PnPEntity'");
    ManagementEventWatcher removeWatcher = new ManagementEventWatcher(removeQuery);
    removeWatcher.EventArrived += new EventArrivedEventHandler(DeviceRemovedEvent);
    removeWatcher.Start();
}

When I inserted the phone to my computer. Two cases of the device received happened.

enter image description here

How do I make it stop on the first instance?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Ken Zhang
  • 21
  • 7
  • What is the question? – JohnSaps Jun 18 '14 at 08:29
  • Make `ManagementEventWatcher insertWatcher` global and put `insertWatcher.Stop()` when device is first detected. When it is removed, put `insertWatcher.Start()` in removed event. – Ricky Jun 18 '14 at 08:29
  • @JohnSaps How do I make it stop at the first instance? – Ken Zhang Jun 18 '14 at 08:33
  • I have tested it and the event is raising only once. There is one case in which the event is raising twice which is, if `backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)` is called twice then two device receive event will be fired. – Ricky Jun 18 '14 at 08:44
  • thanks @Ricky. I got my code working now. – Ken Zhang Jun 18 '14 at 08:49

1 Answers1

0

A rather unclean solution would be something like this:

WqlEventQuery insertQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 3 WHERE     TargetInstance ISA 'Win32_PnPEntity'");
ManagementEventWatcher insertWatcher = new ManagementEventWatcher(insertQuery);

EventArrivedEventHandler eventArrivedhandler = (sender, e) => { };
eventArrivedhandler = (sender, e) =>
{
    insertWatcher.EventArrived -= eventArrivedhandler;
    DeviceInsertedEvent(sender,e);
};
insertWatcher.EventArrived += eventArrivedhandler;
insertWatcher.Start();

I can't say that i like it but it will most likely do the trick.

AndreySarafanov
  • 804
  • 5
  • 20