C# USB plug-in/removal: how to distingwish plug-in and removal ?

P

Polaris

Hi Experts:

I got some C# code from the web which detecting USB plug-in/removal using
System.Managment class (see below); but seems to me the information it
returus is the same for plug-in and removal. Is there a way to distingwish
these two actions using C#?

Thanks In Advance
Polaris

// This code demonstrates how to monitor the UsbControllerDevice for
// the arrival of creation/operation events
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Management;
class WMIEvent {
public static void Main() {
WMIEvent we = new WMIEvent();
ManagementEventWatcher w= null;
WqlEventQuery q;
ManagementOperationObserver observer = new ManagementOperationObserver();
// Bind to local machine
ManagementScope scope = new ManagementScope("root\\CIMV2");
scope.Options.EnablePrivileges = true; //set required privilege
try {
q = new WqlEventQuery();
q.EventClassName = "__InstanceOperationEvent";
q.WithinInterval = new TimeSpan(0,0,3);
q.Condition = @"TargetInstance ISA 'Win32_DiskDrive' ";
w = new ManagementEventWatcher(scope, q);

w.EventArrived += new EventArrivedEventHandler(we.DiskEventArrived);
w.Start();
Console.ReadLine(); // block main thread for test purposes
}
catch(Exception e) {
Console.WriteLine(e.Message);
}
finally {
w.Stop();
}
}
public void DiskEventArrived(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) {
Console.WriteLine("--------------Properties------------------");
foreach(PropertyData prop in mbo.Properties)
Console.WriteLine("{0} - {1}", prop.Name, prop.Value);
}
}
}

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top