The following method is fired when a CD is inserted or ejected.
The problematic code is noted below.
Everything here is based on stepping through the code with breakpoints.
public void CDREventArrived(object sender, EventArrivedEventArgs e) { // Get the Event object and display it PropertyData pd = e.NewEvent.Properties["TargetInstance"]; if (pd != null) { ManagementBaseObject mbo = pd.Value as ManagementBaseObject; if (mbo.Properties["VolumeName"].Value != null) { //This line is executed. textBox1.Text = "test"; //This line is not executed. //While stepping through the execution, //I hit F11 on the line above, //hoping to get to this next line, but it never happens. //The form pops back up and the step through is complete. label1.Text = "test"; } else { //Same problem here. Only the first line is hit. textBox1.Text = "test"; label1.Text = "test"; } } } A related problem is that while it does hit the code to change the text property of textBox1, the text is not actually changed. I can see this on the form and while stepping through breakpoints. So it appears it hits the code, but never actually executes. I'm wondering why it doesn't continue to all the code in the given conditional.
Here is the code which sets up the delegate. This method is called on FormLoad. I stop the listener on form exit.
private void CreateCDRomListener() { WqlEventQuery q; ManagementOperationObserver observer = new ManagementOperationObserver(); // Bind to local machine ConnectionOptions opt = new ConnectionOptions(); opt.EnablePrivileges = true; //sets required privilege ManagementScope scope = new ManagementScope("root\\CIMV2", opt); try { q = new WqlEventQuery(); q.EventClassName = "__InstanceModificationEvent"; q.WithinInterval = new TimeSpan(0, 0, 1); // DriveType - 5: CDROM q.Condition = @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5"; w = new ManagementEventWatcher(scope, q); // register async. event handler w.EventArrived += CDREventArrived; w.Start(); // Do something usefull,block thread for testing Console.ReadLine(); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { } }