"jack" <ja**@mrolinux. com> wrote in message news:eM******** ******@TK2MSFTN GP11.phx.gbl...
Hello,
I'm trying to make a program what can let me know when a USB device is added
or removed from a system. If anyone has any ideas or help that would be
great!
Thanks in advnace,
Jack
Here is a sample using the System.Manageme nt classes (and WMI).
// This code demonstrates how to monitor the UsbControllerDe vice for
// the arrival of creation/operation events
using System;
using System.Componen tModel;
using System.Runtime. InteropServices ;
using System.Manageme nt;
class WMIEvent {
public static void Main() {
WMIEvent we = new WMIEvent();
ManagementEvent Watcher w= null;
WqlEventQuery q;
ManagementOpera tionObserver observer = new ManagementOpera tionObserver();
// Bind to local machine
ManagementScope scope = new ManagementScope ("root\\CIMV2") ;
scope.Options.E nablePrivileges = true; //sets required privilege
try {
q = new WqlEventQuery() ;
q.EventClassNam e = "__InstanceCrea tionEvent";
q.WithinInterva l = new TimeSpan(0,0,10 );
q.Condition = @"TargetInstanc e ISA 'Win32_USBContr ollerDevice' ";
Console.WriteLi ne(q.QueryStrin g);
w = new ManagementEvent Watcher(scope, q);
w.EventArrived += new EventArrivedEve ntHandler(we.Us bEventArrived);
w.Start();
Console.ReadLin e();
}
catch(Exception e) {
Console.WriteLi ne(e.Message);
}
finally {
w.Stop();
}
}
public void UsbEventArrived (object sender, EventArrivedEve ntArgs e) {
//Get the Event object and display it
foreach(Propert yData pd in e.NewEvent.Prop erties) {
Console.WriteLi ne("\n========= =============== ==============" );
Console.WriteLi ne("{0},{1},{2} , {3}",pd.Name, pd.Type, pd.Value, pd.Origin);
ManagementBaseO bject mbo = null;
if(( mbo = pd.Value as ManagementBaseO bject) != null) {
Console.WriteLi ne("--------------Properties------------------");
foreach(Propert yData prop in mbo.Properties)
Console.WriteLi ne("{0} - {1}", prop.Name, prop.Value);
}
}
}
}
Willy.