Below is some code I saw on a vb message board along time ago but I can’t remember where. It may have been vbforums.com. I made some code changes and then tested the code to have it throw a messagebox with the drive letter of the new usb device being attached or removed. It uses application subclassing to intercept the messages and checks if any are activated by a removable volume being Removed, Inserted, Attached, etc.. If it is then it will parse the volume drive letter of the device and throw a messagebox letting you know. USB devices like flash drives (Thumb Drives or Pen Drive’s as they are also called), external hard drives, etc. with a removable disk volume should be detected just fine. My testing recognized different usb volumes with no problems. You can use this code with VB.NET, Visual Basic 2008, VB 2010, 2013, etc. to check for both the arrival of usb volume devices and the removal. You can also make some changes to make it work for VB 6.0 as well. Visual Basic 6.0 will need an addiional API call or two for the subclassing portion.
These go in your declaration section of your program.
' 'The messages to look for. Private Const WM_DEVICECHANGE As Integer = &H219 Private Const DBT_DEVICEARRIVAL As Integer = &H8000 Private Const DBT_DEVICEREMOVECOMPLETE As Integer = &H8004 Private Const DBT_DEVTYP_VOLUME As Integer = &H2 ' ' 'Get the information about the detected volume. Private Structure DEV_BROADCAST_VOLUME Dim Dbcv_Size As Integer Dim Dbcv_Devicetype As Integer Dim Dbcv_Reserved As Integer Dim Dbcv_Unitmask As Integer Dim Dbcv_Flags As Short End Structure
Now for the subclassing based code. This is where it starts to get alittle difficult…