Detecting USB drive insertion and removal using wi

2019-01-02 15:08发布

Looking into possibility of making an USB distributed application
that will autostart on insertion of an USB stick and shutdown when removing the stick

Will use .Net and C#.
Looking for suggestion how to approach this using C#?


Update: Two possible solutions implementing this as a service.
- override WndProc
or
- using WMI query with ManagementEventWatcher

8条回答
泛滥B
2楼-- · 2019-01-02 15:39

Try WM_CHANGEDEVICE handling.

查看更多
初与友歌
3楼-- · 2019-01-02 15:44

Adding to VitalyB's post.

To raise an event where ANY USB device is inserted, use the following:

var watcher = new ManagementEventWatcher();
var query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Query = query;
watcher.Start();

This will raise an event whenever a USB device is plugged. It even works with a National Instruments DAQ that I'm trying to auto-detect.

查看更多
登录 后发表回答