CJLeit Posted March 28, 2006 Posted March 28, 2006 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 isn't 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! Quote
Administrators PlausiblyDamp Posted March 29, 2006 Administrators Posted March 29, 2006 http://msdn.microsoft.com/library/default.asp?url=/library/en-us/devio/base/registering_for_device_notification.asp gives a sample in C on how to register for plug and play events, you might be able to port it to .Net though. http://www.pinvoke.net/default.aspx/user32/RegisterDeviceNotification.html contains a valid DllImport for the function and will get you started. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
jo0ls Posted April 10, 2006 Posted April 10, 2006 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 don't 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 form's 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. I've got some working vb.net code that will identify all usb removable disk drives, and get the "Friendly Name" and path. Vb.net RegisteDeviceNotification exampleVol Arrival.zip Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.