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
San
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
anuraj
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.
Roland
Super A+
Devika
Nice Code!
Thanks a lot..
Daniel
Hello San,
you can use IO.FileSystemWatcher class to monitor the Filesystem on the USB.
by Dani
anuraj
Thank you