使用WMI方式(缺点:不能响应未装驱动的USB设备插拔事件)
using System.Management;
private void InitUSBHandler()
{//监听USB设备插拔
ManagementEventWatcher w = null;
try
{
WqlEventQuery q = new WqlEventQuery
{
Condition = "TargetInstance ISA 'Win32_USBHub'"
};
ManagementScope scope = new ManagementScope(@"root/CIMV2")
{
Options = { EnablePrivileges = true }
};
this.AddRemoveUSBHandler(q, w, scope);
this.AddInsertUSBHandler(q, w, scope);
q = new WqlEventQuery
{
Condition = "TargetInstance ISA 'Win32_DiskDrive'"
};
scope = new ManagementScope(@"root/CIMV2")
{
Options = { EnablePrivileges = true }
};
this.AddRemoveUSBHandler(q, w, scope);
this.AddInsertUSBHandler(q, w, scope);
}
catch (Exception exception)
{
if (w != null)
{
w.Stop();
}
throw exception;
}
}
private void AddInsertUSBHandler(WqlEventQuery q, ManagementEventWatcher w, ManagementScope scope)
{
q.EventClassName = "__InstanceCreationEvent";
q.WithinInterval = new TimeSpan(0, 0, 3);
w = new ManagementEventWatcher(scope, q);
w.EventArrived += new EventArrivedEventHandler(OnUSBInserted);
w.Start();
}
private void AddRemoveUSBHandler(WqlEventQuery q, ManagementEventWatcher w, ManagementScope scope)
{
q.EventClassName = "__InstanceDeletionEvent";
q.WithinInterval = new TimeSpan(0, 0, 1);
w = new ManagementEventWatcher(scope, q);
w.EventArrived += new EventArrivedEventHandler(OnUSBRemoved);
w.Start();
}
private void ScanDevices()
{//扫描USB设备(方法一)
if (this._compisiteDeviceList.Count == 0)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PnPEntity where DeviceID like 'USB%'");
foreach (ManagementObject obj2 in searcher.Get())
{
string id = obj2.Properties["DeviceID"].Value.ToString();
}
}
}
private void ScanDevices2()
{//扫描USB设备(方法二)
ManagementPath path = new ManagementPath
{
Server = ".",
NamespacePath = @"root/CIMV2",
RelativePath = "Win32_USBHub"
};
using (ManagementClass class2 = new ManagementClass(new ManagementScope(path), path, new ObjectGetOptions(null, new TimeSpan(0, 0, 0, 2), true)))
{
foreach (ManagementObject obj2 in class2.GetInstances())
{
string str = obj2.Properties["Name"].Value.ToString();
string str1 = (string)obj2["CreationClassName"];
string str2 = (string)obj2["Caption"];
string str3 = (string)obj2["PNPDeviceID"];
string str4 = (string)obj2["Description"];
//string str5 = (string)obj2["Service"];
string str6 = (string)obj2["DeviceID"];
}
}
}