您可以使用ManagementEventWatcher
.
LinqPad的工作示例解释了这个简洁的答案,它使用Win32_DeviceChangeEvent
:
// using System.Management;
// reference System.Management.dll
void Main()
{
using(var control = new USBControl()){
Console.ReadLine();//block - depends on usage in a Windows (NT) Service, WinForms/Console/Xaml-App, library
}
}
class USBControl : IDisposable
{
// used for monitoring plugging and unplugging of USB devices.
private ManagementEventWatcher watcherAttach;
private ManagementEventWatcher watcherDetach;
public USBControl()
{
// Add USB plugged event watching
watcherAttach = new ManagementEventWatcher();
watcherAttach.EventArrived += Attaching;
watcherAttach.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");
watcherAttach.Start();
// Add USB unplugged event watching
watcherDetach = new ManagementEventWatcher();
watcherDetach.EventArrived += Detaching;
watcherDetach.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3");
watcherDetach.Start();
}
public void Dispose()
{
watcherAttach.Stop();
watcherDetach.Stop();
//you may want to yield or Thread.Sleep
watcherAttach.Dispose();
watcherDetach.Dispose();
//you may want to yield or Thread.Sleep
}
void Attaching(object sender, EventArrivedEventArgs e)
{
if(sender!=watcherAttach)return;
e.Dump("Attaching");
}
void Detaching(object sender, EventArrivedEventArgs e)
{
if(sender!=watcherDetach)return;
e.Dump("Detaching");
}
~USBControl()
{
this.Dispose();// for ease of readability I left out the complete Dispose pattern
}
}
连接 USB 棒时,我将收到 7 个附加(分别为分离)事件。根据需要自定义附加/分离方法。阻塞部分留给读者,根据他的需要,你根本不需要阻塞的 Windows 服务。