I wrote this code a few weeks ago
Imports System.Runtime.InteropServices
#Region "Constants"
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
#End Region
#Region "Structures"
Private Structure DEV_BROADCAST_HDR
Public dbch_size As Int32
Public dbch_devicetype As Int32
Public dbch_reserved As Int32
End Structure
Private Structure DEV_BROADCAST_VOLUME
Public dbcv_size As Int32
Public dbcv_devicetype As Int32
Public dbcv_reserved As Int32
Public dbcv_unitmask As Int32
Public dbcv_flags As Int32
End Structure
#End Region
#Region "WndProc (SUB)"
Protected Overrides Sub WndProc(ByRef m As Message)
' Windows MESSAGE
If m.Msg = WM_DEVICECHANGE Then
' Check to see if device was plugged in
If m.WParam.ToInt32() = DBT_DEVICEARRIVAL Then
Dim hdr As DEV_BROADCAST_HDR =
CType(Marshal.PtrToStructure(m.LParam, GetType(DEV_BROADCAST_HDR)),
DEV_BROADCAST_HDR)
' See if the device is a USB Flash Drive etc.
If hdr.dbch_devicetype = DBT_DEVTYP_VOLUME Then
' Declare volume as structure
Dim vol As DEV_BROADCAST_VOLUME =
CType(Marshal.PtrToStructure(m.LParam, GetType(DEV_BROADCAST_VOLUME)),
DEV_BROADCAST_VOLUME)
' Get volume number
Dim mask As Int32 = vol.dbcv_unitmask
' Get the drive letter
Dim chDriveLetter As Char() = GetDriveLetter(mask)
' Display the drive letter
lblDrive.Text = String.Format("USB Flash Drive Plugged
Into {0}:", chDriveLetter(0).ToString().ToUpper())
End If
ElseIf m.WParam.ToInt32() = DBT_DEVICEREMOVECOMPLETE Then
' Flash Drive Unplugged
lblDrive.Text = "USB Flash Drive Removed"
End If
End If
MyBase.WndProc(m)
End Sub
#End Region
#Region "Get Drive Letter (FUNCTION)"
Private Function GetDriveLetter(ByVal iChar As Int32) As Char()
Dim cnt As Integer = 0
Dim intTemp As Int32 = iChar
Dim i As Integer
For i = 0 To 31
If (intTemp And 1) = 1 Then
cnt += 1
End If
intTemp = (intTemp >> 1)
If intTemp = 0 Then
Exit For
End If
Next
Dim chResult(0) As Char
Dim ii As Integer
For ii = 0 To 31
If (iChar And 1) = 1 Then
chResult(0) = Chr(97 + ii)
End If
iChar = (iChar >> 1)
If iChar = 0 Then
Exit For
End If
Next
Return chResult
End Function
#End Region