I am trying to monitor drives a local PC. I am interested in two events: when the drive is connected (USB drive, CD-ROM, Network Drive, etc.) and disconnected. I wrote a quick proof of concept using the ManagementOperationObserver and it partially works. Right now (with the code below), I am getting all sort of events. I would like to get only events when a drive is connected and disconnected. Is there a way to specify this in the Wql Query?
Thanks!
private void button2_Click(object sender, EventArgs e)
{
t = new Thread(new ParameterizedThreadStart(o =>
{
WqlEventQuery q;
ManagementOperationObserver observer = new ManagementOperationObserver();
ManagementScope scope = new ManagementScope("root\\CIMV2");
scope.Options.EnablePrivileges = true;
q = new WqlEventQuery();
q.EventClassName = "__InstanceOperationEvent";
q.WithinInterval = new TimeSpan(0, 0, 3);
q.Condition = @"TargetInstance ISA 'Win32_LogicalDisk' ";
w = new ManagementEventWatcher(scope, q);
w.EventArrived += new EventArrivedEventHandler(w_EventArrived);
w.Start();
}));
t.Start();
}
void w_EventArrived(object sender, EventArrivedEventArgs e)
{
//Get the Event object and display its properties (all)
foreach (PropertyData pd in e.NewEvent.Properties)
{
ManagementBaseObject mbo = null;
if ((mbo = pd.Value as ManagementBaseObject) != null)
{
this.listBox1.BeginInvoke(new Action(() => listBox1.Items.Add("--------------Properties------------------")));
foreach (PropertyData prop in mbo.Properties)
this.listBox1.BeginInvoke(new Action<PropertyData>(p => listBox1.Items.Add(p.Name + " - " + p.Value)), prop);
}
}
}