Detect insertion of media into a drive using windo

2019-01-23 08:55发布

I am currently using WM_DEVICECHANGE to be notified when new USB drives are connected to the computer. This works great for devices like thumb-drives where as soon as the device arrives it is ready to have files read from it. For devices like SD card readers it does not because the message is sent out once when the device is connected but no message is sent when a user actually inserts a card into the device.

Is it possible to detect the insertion of new media into an existing USB device without having to use polling?

4条回答
聊天终结者
2楼-- · 2019-01-23 09:22

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

查看更多
The star\"
3楼-- · 2019-01-23 09:23

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.

查看更多
smile是对你的礼貌
4楼-- · 2019-01-23 09:28

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.

查看更多
Ridiculous、
5楼-- · 2019-01-23 09:38

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!

查看更多
登录 后发表回答