I create two handlers to receive USB device plug/unplug events, similar to this answer.
private void RegisterUSBEvents()
{
WqlEventQuery insertQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 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 2 WHERE TargetInstance ISA 'Win32_PnPEntity'");
ManagementEventWatcher removeWatcher = new ManagementEventWatcher(removeQuery);
removeWatcher.EventArrived += new EventArrivedEventHandler(DeviceRemovedEvent);
removeWatcher.Start();
}
I could receive any USB plug or unplug event using above code.
For most PCs, after windows wake up from hibernation, my app will receive a InstanceDeletionEvent
, following by a InstanceCreationEvent
for a USB device.
However, on few computers, after windows hibernates and wakes up, I could only receive a InstanceDeletionEvent
, but no InstanceCreationEvent
for the same device. The USB device is leaved on the USB port untouched.
If I close and restart my app, or unplug/plug the same device, the above code becomes working again.
Is there any problem causing a USB device fire InstanceDeletionEvent
but not fire InstanceCreationEvent
after hibernation in certain environment?