I am working on a project in which I need to determine when a CD or USB drive is inserted or removed. I found some source code that should have done just that, but nothing happens when I insert or remove the CD.
Can someone confirm that the source is right and give me any guidance as to what I may have done wrong?
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"];
}
}
When I set a breakpoint on the line "PropertyData pd = ...", it never hits when I eject / insert a CD. Since I did not communicate with this at all, and all the examples that I saw on the Internet just reference the same source code (with slight variations)
source
share