the below code worked for me. it subscribes to both DriveType=2 and DriveType=5 events to detect cd-rom and usb. since i do not need to know whether the drive was mounted or unmounted or cd was removed or inserted, the code does not check for that. for usb mounts e.NewEvent.ClassPath can be used to tell whether drive was connected or disconnected.
also, i found some confusing remarks on the internet saying that subscribing to events for DriveType=5 alone would detect usb mounts as well. this did not work for me.
konstantin
using System;
using System.Management;
namespace consapp
{
class Program
{
static void Main(string[] args)
{
const string QUERY = @"select * from __InstanceOperationEvent within 1 where TargetInstance isa 'Win32_LogicalDisk' and (TargetInstance.DriveType=2 or TargetInstance.DriveType=5)";
Program p = new Program();
ManagementEventWatcher w = new ManagementEventWatcher(new WqlEventQuery(QUERY));
w.EventArrived += new EventArrivedEventHandler(p.OnWMIEvent);
w.Start();
Console.ReadKey();
w.Stop();
}
public void OnWMIEvent(object sender, EventArrivedEventArgs e)
{
PropertyData p = e.NewEvent.Properties["TargetInstance"];
if (p != null)
{
ManagementBaseObject mbo = p.Value as ManagementBaseObject;
PropertyData deviceid = mbo.Properties["DeviceID"];
PropertyData drivetype = mbo.Properties["DriveType"];
Console.WriteLine("{0}-{1}:{2}", deviceid.Value, drivetype.Value, e.NewEvent.ClassPath);
}
}
}
}