Détection d’éjection / insertion de support amovible

Je travaille sur un projet dans lequel je dois être capable de détecter lorsqu’un CD ou une clé USB est inséré ou retiré. J’ai trouvé un code source qui était supposé faire exactement cela, cependant, rien ne semble se passer lorsque j’insère ou éjecte un CD.

Quelqu’un pourrait-il s’il vous plaît vérifier que la source est correcte et me donner des indications sur ce que j’ai pu faire de mal ici?

public class MyWindow { ManagementEventWatcher w; private void MyWindow_Loaded(object sender, RoutedEventArgs e) { WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 2"); ConnectionOptions opt = new ConnectionOptions(); opt.EnablePrivileges = true; ManagementScope ms = new ManagementScope("root\\CIMV2", opt); w = new ManagementEventWatcher(ms, query); w.EventArrived += new EventArrivedEventHandler(w_EventArrived); w.Start(); } private void w_EventArrived(object sender, EventArrivedEventArgs e) { PropertyData pd = e.NewEvent.Properties["TargetInstance"]; } } 

Lorsque je définis un point d’arrêt sur la ligne “PropertyData pd = …”, il n’est jamais touché lorsque j’éjecte / insère un CD. Comme je n’ai pas du tout gâché cela, et tous les exemples que j’ai vus en ligne citent simplement ce même code source (avec des variations mineures)

 using System.Management; public void networkDevice() { try { WqlEventQuery q = new WqlEventQuery(); q.EventClassName = "__InstanceModificationEvent"; q.WithinInterval = new TimeSpan(0, 0, 1); q.Condition = @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5"; ConnectionOptions opt = new ConnectionOptions(); opt.EnablePrivileges = true; opt.Authority = null; opt.Authentication = AuthenticationLevel.Default; //opt.Username = "Administrator"; //opt.Password = ""; ManagementScope scope = new ManagementScope("\\root\\CIMV2", opt); ManagementEventWatcher watcher = new ManagementEventWatcher(scope, q); watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); watcher.Start(); } catch (ManagementException e) { Console.WriteLine(e.Message); } } void watcher_EventArrived(object sender, EventArrivedEventArgs e) { ManagementBaseObject wmiDevice = (ManagementBaseObject)e.NewEvent["TargetInstance"]; ssortingng driveName = (ssortingng)wmiDevice["DeviceID"]; Console.WriteLine(driveName); Console.WriteLine(wmiDevice.Properties["VolumeName"].Value); Console.WriteLine((ssortingng)wmiDevice["Name"]); if (wmiDevice.Properties["VolumeName"].Value != null) Console.WriteLine("CD has been inserted"); else Console.WriteLine("CD has been ejected"); }