Detect insertion of media into a drive using windows messages

荒凉一梦 提交于 2019-11-29 00:12:24

I just did this a few weeks ago. Technically speaking the RegisterDeviceNotification route is the proper way to go, but it requires a decent amount of work to get right. However, Windows Explorer already does all of the hard work for you. Just use SHChangeNotifyRegister with SHCNE_DRIVEADD / SHCNE_DRIVEREMOVED / SHCNE_MEDIAINSERTED / SHCNE_MEDIAREMOVED. Note that this method depends on the Shell Hardware Detection service (or whatever it is called), but it's much easier than trying to re-implement the functionality yourself.

caesarvanou

There is a very good example of the usage of SHChangeNotifyRegister in the "Change Notify Watcher Sample". Download it from this address:

http://msdn.microsoft.com/en-us/library/dd940348.aspx#downloading

I implemented SHChangeNotifyRegister in my Qt code.

Thanks to Luke for his very good answer!

Could be a bug in the SD reader driver. The description in WM_DEVICECHANGE is "DBT_DEVICEARRIVAL 0x8000 A device or piece of media has been inserted and is now available."

Therefore, you're supposed to get a notification for media insertion.

Did you try using RegisterDeviceNotification? Only some notifications are sent by default, and media change might not be one of them.

Quin Arnold

Perhaps it is a bug in the device drivers (I certainly think it is), but they all appear to work in the same way... NOT. So at this point I don't think you can get any device driver devlopers to change their device characteristices even if Microsoft (probably the largest developer) leads you to believe it should work this way (Not working for my Windows7 microsoft driver). The insertion of an SD card into a USB device simply does not trigger a WM_DEVICECHANGE message.

Use SHChangeNotifyRegister for media type devices. It does not require a register devicenotification. And you can get the drive letter via SHGetPathFromIDList. Use SHCNE_MEDIAINSERTED and SHCNE_MEDIAREMOVED.

Use device ONDeviceNotify if you are looking for a hardware device rather than a media device, or you might be able to write a device driver of your own.

See this comment's code CodeProject - Trapping windows messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!