Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. private const string deviceSelectWmiQuery = @"SELECT * FROM Win32_PnPEntity where DeviceID Like 'USB%' AND Name Like '%Apple Mobile Device USB%'";
  2. private const string deviceOperationWmiQuery = @"SELECT * FROM __InstanceOperationEvent WITHIN 3 WHERE TargetInstance ISA 'Win32_PnPEntity' AND TargetInstance.Name Like '%Apple Mobile Device USB%'"; // Win32_USBHub
  3. private ManagementEventWatcher usbDeviceWatcher;
  4. //...
  5. var usbDeviceOperationQuery = new WqlEventQuery(deviceOperationWmiQuery);
  6. var scope = new ManagementScope("root\\CIMV2");
  7. usbDeviceWatcher = new ManagementEventWatcher(scope, usbDeviceOperationQuery);
  8.  
  9. public void WatchUsbDevices()
  10. {
  11. if (pollingTimer.IsEnabled)
  12. {
  13. StopWatchingUsbDevices();
  14. }
  15.  
  16. usbDeviceWatcher.EventArrived += UsbDeviceOperationEvent;
  17. usbDeviceWatcher.Start();
  18.  
  19. pollingTimer.Start();
  20. }
  21.  
  22. public void StopWatchingUsbDevices()
  23. {
  24. usbDeviceWatcher.EventArrived -= UsbDeviceOperationEvent;
  25. usbDeviceWatcher?.Stop();
  26.  
  27. pollingTimer?.Stop();
  28. }
  29.  
  30. private void UsbDeviceOperationEvent(object sender, EventArrivedEventArgs e)
  31. {
  32. var usbDeviceInstance = e.NewEvent["TargetInstance"] as ManagementBaseObject;
  33. if (usbDeviceInstance != null)
  34. {
  35. if (e.NewEvent.ClassPath.ClassName.Equals("__InstanceCreationEvent"))
  36. {
  37. UsbDeviceInsertedEvent(sender, usbDeviceInstance);
  38. }
  39. else if(e.NewEvent.ClassPath.ClassName.Equals("__InstanceDeletionEvent"))
  40. {
  41. UsbDeviceRemovedEvent(sender, usbDeviceInstance);
  42. }
  43. }
  44. }
  45.  
  46. private void UsbDeviceInsertedEvent(object sender, ManagementBaseObject usbDeviceInstance)
  47. {
  48. var deviceID = (usbDeviceInstance.GetPropertyValue("DeviceID") as string)?.ToLower();
  49. // targetObject.Dispatcher.Invoke(() => { targetDevices.Add(device); });
  50. }
  51.  
  52. private void UsbDeviceRemovedEvent(object sender, ManagementBaseObject instance)
  53. {
  54. var deviceID = (instance.GetPropertyValue("DeviceID") as string)?.ToLower();
  55. // targetObject.Dispatcher.Invoke(() => targetDevices.Remove(deviceToRemove.First()));
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement