Home > .Net, .Net 3.0 / 3.5, Visual Studio, Win 32 API > How to detect USB insertion and removal in VB.Net

How to detect USB insertion and removal in VB.Net

Recently I moved to a Desktop application development team, where I have to look for the insertion of the USB. I need to read the contents of the USB drive and updates the application. I got a lot of solutions from Google to detect the USB insertion and removal. I am posting the easiest one I found, it is VB.Net, but I don’t think we can use it Class Libraries, and we may need to use the Windows Forms.

    Private WM_DEVICECHANGE As Integer = &H219

    Public Enum WM_DEVICECHANGE_WPPARAMS As Integer
        DBT_CONFIGCHANGECANCELED = &H19
        DBT_CONFIGCHANGED = &H18
        DBT_CUSTOMEVENT = &H8006
        DBT_DEVICEARRIVAL = &H8000
        DBT_DEVICEQUERYREMOVE = &H8001
        DBT_DEVICEQUERYREMOVEFAILED = &H8002
        DBT_DEVICEREMOVECOMPLETE = &H8004
        DBT_DEVICEREMOVEPENDING = &H8003
        DBT_DEVICETYPESPECIFIC = &H8005
        DBT_DEVNODES_CHANGED = &H7
        DBT_QUERYCHANGECONFIG = &H17
        DBT_USERDEFINED = &HFFFF
    End Enum

    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        If m.Msg = WM_DEVICECHANGE Then
            Select Case m.WParam
                Case WM_DEVICECHANGE_WPPARAMS.DBT_DEVICEARRIVAL
                    lblMessage.Text = "USB Inserted"
                Case WM_DEVICECHANGE_WPPARAMS.DBT_DEVICEREMOVECOMPLETE
                    lblMessage.Text = "USB Removed"
            End Select
        End If
        MyBase.WndProc(m)
    End Sub

The code is pretty clear; I am overriding the WndProc method. When a USB inserted or removed, Windows will send some message (WM_DEVICECHANGE) to all the applications. And the WParam property of that message will contains the details of the device event. The system broadcasts the DBT_DEVICEARRIVAL device event when a device or piece of media has been inserted and becomes available. The system broadcasts the DBT_DEVICEREMOVECOMPLETE device event when a device or piece of media has been physically removed.

Now I am looking into how can remove a USB programmatically.

  1. San
    April 7th, 2009 at 05:20 | #1

    The code you have presented is good.Its work Fine.And one more query is it possible to read the files that are copied to the USB device.?

    Thanks

  2. April 10th, 2009 at 09:54 | #2

    Thanks for the comments [:)]. Sorry I didn’t get you exactly what you mean by read files copied to USB? You can put a FileWatcher and get the details of the Files Copied, Deleted, Moved, Updated, created etc.

  3. Roland
    September 17th, 2009 at 17:28 | #3

    Super A+

  4. September 17th, 2009 at 18:42 | #4

    Thank you :)

  1. No trackbacks yet.