How to detect USB insertion and removal in VB.Net

You can find the USB insertion and removal using WIN32 API as well as WMI. This post is about detecting USB insert and removal using WIN32 API.

    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 WndProc() helps to detect Windows Messages from OS. When a USB inserted or removed, Windows OS 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.

Happy Programming

6 thoughts on “How to detect USB insertion and removal in VB.Net

  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. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA Image

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>