Event for USB drive connection

CJLeit

Active member
Joined
Feb 1, 2006
Messages
32
Is there a way to trap when a USB drive is plugged into the computer. Right now I just have a timer that checks every 15 seconds to see if my drive is plugged in. This isnt a very good solution. I was hoping there is a way to have an event fired whenever a new USB device is plugged in or a new drive is add.

Thanks!
 
RegisterDeviceNotification would let you find out when a USB device was plugged in, you send the forms handle and get alerted via WM_DEVICECHANGE messages. You dont need to register for notifications of volume changes or port changes - it happens automatically. So you can actually skip registering.
To read the message then:
override WndProc, and check for WM_DEVICECHANGE.
The Wparam will tell you if it is an arrival or removal.
The LParam is a structure that depends on the type of DEVICECHANGE that is occuring. The start of the structure is the same for all device types, DEV_BROADCAST_HDR. The header tells us the device type, so if it is a volume then we can convert Lparam to a DEV_BROADCAST_VOLUME structure. This structure has a field that stores the device(s) drive letter.

See attached c#, or bad vb.net. Note, you can use a NativeWindow class and handle its WndProc instead of the forms one. Makes it tidier...

If you need to test to see if it is a usb device (just detecting volumes will detect CDs etc...), then it gets complicated. this is a good starting point. Ive got some working vb.net code that will identify all usb removable disk drives, and get the "Friendly Name" and path.
Vb.net RegisteDeviceNotification example
 

Attachments

Back
Top