简体   繁体   中英

C# USB removal event in Windows XP

I am developing a C# class library for a USB-Serial device. I need an event to know when is the USB being removed.

Currently I am using WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3") to get notified when the USB is being removed, so that I can disconnect the port after it is unplugged.

This works fine in Windows 7, windows 8 and windows 10. But in Windows XP SP3, the event does not get triggered when the USB is being removed. (Remark: My windows XP is installed with .NET 3.5 and .NET 3.5 SP1)

Is there a way I able to get notified when the USB is being removed in Windows XP?

I found the solution !

string query = "SELECT * FROM __InstanceDeletionEvent WITHIN [interval] WHERE TargetInstance ISA 'Win32_USBHub'";
var watcher = new ManagementEventWatcher(query);
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Start();

Remark: Replace [interval] to specify a polling interval, which you may get more information HERE .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM