C# 监听usb插拔
private static ManagementEventWatcher insertWatcher; private static ManagementEventWatcher removeWatcher; static void Main(string[] args) { insertWatcher = new ManagementEventWatcher(); WqlEventQuery insertQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_USBControllerDevice'"); insertWatcher.EventArrived += USBDeviceInserted; insertWatcher.Query = insertQuery; insertWatcher.Start(); removeWatcher = new ManagementEventWatcher(); WqlEventQuery removeQuery = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_USBControllerDevice'"); removeWatcher.EventArrived += USBDeviceRemoved; removeWatcher.Query = removeQuery; removeWatcher.Start(); Console.ReadKey(); StopMonitoring(); Console.WriteLine("OK"); Console.ReadKey(); } private static void USBDeviceInserted(object sender, EventArrivedEventArgs e) { ManagementBaseObject targetInstance = (ManagementBaseObject)e.NewEvent["TargetInstance"]; string deviceId = targetInstance["Dependent"] as string; if (deviceId.Contains("VID_04B4") && deviceId.Contains("PID_1003")) { } } private static void USBDeviceRemoved(object sender, EventArrivedEventArgs e) { ManagementBaseObject targetInstance = (ManagementBaseObject)e.NewEvent["TargetInstance"]; string deviceId = targetInstance["Dependent"] as string; if (deviceId.Contains("VID_04B4") && deviceId.Contains("PID_1003")) { } } private static void StopMonitoring() { if (insertWatcher != null) { insertWatcher.Stop(); insertWatcher.Dispose(); insertWatcher = null; } if (removeWatcher != null) { removeWatcher.Stop(); removeWatcher.Dispose(); removeWatcher = null; } }