We help IT Professionals succeed at work.

how to detect removable drive (pen drive)

crystalsoft
crystalsoft used Ask the Experts™
on

How to detect removable drive using vb code

Thanks

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Author

Commented:

but except cd or dvd drive..




Top Expert 2010

Commented:
What exactly are you looking for a way to enumerate all usb drives  or to actually detect when a usb has been inserted/removed.

Commented:
You can use WIndows Management Instrumentation (WMI) to detect the insertion / removal of a USB-based storage device.
I have a VB.Net source code example (I know you're asking for VB6, but it might be of some help)

Imports System.Management

    Private WithEvents m_MediaConnectWatcher As ManagementEventWatcher

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ' __InstanceOperationEvent will trap both Creation and Deletion of class instances
        Dim query2 As String = "SELECT * FROM __InstanceOperationEvent WITHIN 10 WHERE TargetInstance ISA ""Win32_DiskDrive"""
        m_MediaConnectWatcher = New ManagementEventWatcher(query2)
        m_MediaConnectWatcher.Start()
    End Sub


    Private Sub Arrived(ByVal sender As Object, ByVal e As System.Management.EventArrivedEventArgs) Handles m_MediaConnectWatcher.EventArrived
        Dim mbo, obj As ManagementBaseObject

        ' the first thing we have to do is figure out if this is a creation or deletion event
        mbo = CType(e.NewEvent, ManagementBaseObject)
        ' next we need a copy of the instance that was either created or deleted
        obj = CType(mbo("TargetInstance"), ManagementBaseObject)

        Select Case mbo.ClassPath.ClassName
            Case "__InstanceCreationEvent"
                If obj("InterfaceType") = "USB" Then
                    MsgBox(obj("Caption") & " has been plugged in")
                End If
            Case "__InstanceDeletionEvent"
                If obj("InterfaceType") = "USB" Then
                    MsgBox(obj("Caption") & " has been unplugged")
                End If
        End Select

    End Sub

Open in new window

Author

Commented:
egl1044: actually detect when a usb has been inserted/removed.

Yes i am looking for usb has ben inserted or not



Top Expert 2010
Commented:
You can register device notifications for USB device by registering the usb guid and checking for WM_DEVICECHANGE message. see code section for an API version.

' 
' //                   Module1.bas
' 

Option Explicit

'egl1044
Private Const GWL_WNDPROC                As Long = (-4)
Private Const WM_DEVICECHANGE            As Long = &H219
Private Const DBT_DEVICEARRIVAL          As Long = 32768
Private Const DBT_DEVICEREMOVECOMPLETE   As Long = 32772
Private Const DBT_DEVTYP_DEVICEINTERFACE As Long = &H5&
Private Const DBT_DEVTYP_VOLUME          As Long = &H2&
Private Const GUID_USB                   As String = "{A5DCBF10-6530-11D2-901F-00C04FB951ED}"

Private Type UUID
Data1               As Long
Data2               As Integer
Data3               As Integer
Data4(7)            As Byte
End Type
 
Private Type DEV_BROADCAST_HDR
dbch_size           As Long
dbch_devicetype     As Long
dbch_reserved       As Long
End Type
 
Private Type DEV_BROADCAST_DEVICEINTERFACE
dbcc_size           As Long
dbcc_devicetype     As Long
dbcc_reserved       As Long
dbcc_classguid      As UUID
dbcc_name           As Long
End Type
 
Private Type DEV_BROADCAST_VOLUME
dbcv_size           As Long
dbcv_devicetype     As Long
dbcv_reserved       As Long
dbcv_unitmask       As Long
dbcv_flags          As Integer
End Type
 
Private Declare Function CallWindowProcW Lib "User32.dll" ( _
    ByVal lpPrevWndFunc As Long, _
    ByVal hWnd As Long, _
    ByVal uMsg As Long, _
    ByVal wParam As Long, _
    ByVal lParam As Long) As Long
    
Private Declare Function SetWindowLongW Lib "User32.dll" ( _
    ByVal hWnd As Long, _
    ByVal nIndex As Long, _
    ByVal dwNewLong As Long) As Long
    
Private Declare Function RegisterDeviceNotificationW Lib "User32.dll" ( _
    ByVal hRecipient As Long, _
    ByVal NotificationFilter As Long, _
    ByVal Flags As Long) As Long

Private Declare Function UnregisterDeviceNotification Lib "User32.dll" ( _
    ByVal Handle As Long) As Long

Private Declare Function CLSIDFromString Lib "Ole32.dll" ( _
    ByVal lpsz As Long, _
    ByRef pclsid As UUID) As Long

Private Declare Sub RtlMoveMemory Lib "Kernel32.dll" ( _
    ByRef Destination As Any, _
    ByRef Source As Any, _
    ByVal Length As Long)
    
Private Declare Sub RtlZeroMemory Lib "Kernel32.dll" ( _
    ByRef dst As Any, _
    ByVal nBytes As Long)
 

Public func         As Long
Public hDev         As Long
Public hWindow      As Long

Dim lpdb            As DEV_BROADCAST_HDR
Dim lpdbv           As DEV_BROADCAST_VOLUME
Dim lpdbdi          As DEV_BROADCAST_DEVICEINTERFACE
Dim fUsb            As Boolean

Private Function GetDriveFromMask(ByVal UnitMask As Long) As String
    GetDriveFromMask = Chr$(65 + (Log(UnitMask) / Log(2)))
End Function
 
Public Sub RegisterDeviceInterfaceToHwnd(ByVal hWnd As Long)
    Dim lpdbd       As DEV_BROADCAST_DEVICEINTERFACE
    Dim lpusb       As UUID
    If func <> 0 Then
        Exit Sub
    End If
    hWindow = hWnd
    CLSIDFromString StrPtr(GUID_USB), lpusb
    lpdbd.dbcc_size = Len(lpdbd)
    lpdbd.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE
    lpdbd.dbcc_classguid = lpusb
    hDev = RegisterDeviceNotificationW(hWindow, VarPtr(lpdbd), 0)
    func = SetWindowLongW(hWindow, GWL_WNDPROC, AddressOf OnUsbChange)
End Sub
 
Public Sub UnRegisterDeviceInterface()
    UnregisterDeviceNotification hDev
    func = SetWindowLongW(hWindow, GWL_WNDPROC, func)
    func = 0
    hWindow = 0
End Sub
 
Public Function OnUsbChange(ByVal hWnd As Long, ByVal uMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

    If uMsg = WM_DEVICECHANGE Then
    
        Select Case wParam
        
            Case DBT_DEVICEARRIVAL
                RtlMoveMemory lpdb, ByVal lParam&, Len(lpdb)
                
                If lpdb.dbch_devicetype = DBT_DEVTYP_DEVICEINTERFACE Then
                    RtlMoveMemory lpdbdi, ByVal lParam&, Len(lpdbdi)
                    fUsb = True
                End If
                
                If lpdb.dbch_devicetype = DBT_DEVTYP_VOLUME And fUsb Then
                    RtlMoveMemory lpdbv, ByVal lParam&, Len(lpdbv)
                    fUsb = False
                    '                       Inserted
                    Debug.Print "Inserted @ drive= " & GetDriveFromMask(lpdbv.dbcv_unitmask)
                End If
                
            Case DBT_DEVICEREMOVECOMPLETE
                RtlMoveMemory lpdb, ByVal lParam&, Len(lpdb)
                
                If lpdb.dbch_devicetype = DBT_DEVTYP_DEVICEINTERFACE Then
                    RtlMoveMemory lpdbdi, ByVal lParam&, Len(lpdbdi)
                     fUsb = True
                End If
                
                If lpdb.dbch_devicetype = DBT_DEVTYP_VOLUME And fUsb Then
                    RtlMoveMemory lpdbv, ByVal lParam&, Len(lpdbv)
                    fUsb = False
                    '                       Removed
                    Debug.Print "Removed @ drive= " & GetDriveFromMask(lpdbv.dbcv_unitmask)
                End If
                
        End Select
    End If
    OnUsbChange = CallWindowProcW(func, hWnd, uMsg, wParam, lParam)
End Function








'
' //              Form1.frm
'

Option Explicit

Private Sub Form_Load()
    Call RegisterDeviceInterfaceToHwnd(Me.hWnd)
End Sub
 
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
    Call UnRegisterDeviceInterface
End Sub

Open in new window

Author

Commented:

But anyway

hes: >>> gave me good example
and i modified and its working exactly i want...
Obviously Total Credit Goes to Code Writer..

egl1044: >>> your code is very useful for my another project.

Thanks