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.
How do I make it stop on the first instance?