Guest User

Untitled

a guest
Apr 23rd, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. public class MyWindow
  2. {
  3. ManagementEventWatcher w;
  4.  
  5. private void MyWindow_Loaded(object sender, RoutedEventArgs e)
  6. {
  7. WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 2");
  8. ConnectionOptions opt = new ConnectionOptions();
  9. opt.EnablePrivileges = true;
  10.  
  11. ManagementScope ms = new ManagementScope("root\CIMV2", opt);
  12.  
  13. w = new ManagementEventWatcher(ms, query);
  14.  
  15. w.EventArrived += new EventArrivedEventHandler(w_EventArrived);
  16. w.Start();
  17. }
  18.  
  19. private void w_EventArrived(object sender, EventArrivedEventArgs e)
  20. {
  21. PropertyData pd = e.NewEvent.Properties["TargetInstance"];
  22. }
  23. }
  24.  
  25. public void networkDevice()
  26. {
  27. try
  28. {
  29. WqlEventQuery q = new WqlEventQuery();
  30. q.EventClassName = "__InstanceModificationEvent";
  31. q.WithinInterval = new TimeSpan(0, 0, 1);
  32. q.Condition = @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5";
  33.  
  34. ConnectionOptions opt = new ConnectionOptions();
  35. opt.EnablePrivileges = true;
  36. opt.Authority = null;
  37. opt.Authentication = AuthenticationLevel.Default;
  38. //opt.Username = "Administrator";
  39. //opt.Password = "";
  40. ManagementScope scope = new ManagementScope("\root\CIMV2", opt);
  41.  
  42. ManagementEventWatcher watcher = new ManagementEventWatcher(scope, q);
  43. watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
  44. watcher.Start();
  45. }
  46. catch (ManagementException e)
  47. {
  48. Console.WriteLine(e.Message);
  49. }
  50. }
  51.  
  52. void watcher_EventArrived(object sender, EventArrivedEventArgs e)
  53. {
  54. ManagementBaseObject wmiDevice = (ManagementBaseObject)e.NewEvent["TargetInstance"];
  55. string driveName = (string)wmiDevice["DeviceID"];
  56. Console.WriteLine(driveName);
  57. Console.WriteLine(wmiDevice.Properties["VolumeName"].Value);
  58. Console.WriteLine((string)wmiDevice["Name"]);
  59. if (wmiDevice.Properties["VolumeName"].Value != null)
  60. Console.WriteLine("CD has been inserted");
  61. else
  62. Console.WriteLine("CD has been ejected");
  63. }
Add Comment
Please, Sign In to add comment