Reputation: 233
Instead of the FileSystemWachter Class I am looking something similar that looks when a new drive letter pop-up. For example when a usb disk is attached or an SD-Card is inserted etc you will get a new drive letter. I would like to have an event in my app when this is happening.
Can you use the FileSystemWatcher class for this or is there something specific for this?
Any examples or suggestions?
Upvotes: 2
Views: 1300
Reputation: 11773
Here is a solution using a timer. This is not specific to USB type devices.
Dim WithEvents myTimer As New Timers.Timer
Private Sub Form1_Shown(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Shown
'start a timer to watch for new drives
myTimer.Interval = 1000
myTimer.AutoReset = True
myTimer.Start()
drvs.AddRange(IO.Directory.GetLogicalDrives) 'get initial set of drives
End Sub
Dim drvs As New List(Of String)
Private Sub myTimer_Elapsed(ByVal sender As Object, _
ByVal e As System.Timers.ElapsedEventArgs) Handles myTimer.Elapsed
Dim cDrvs As New List(Of String)(IO.Directory.GetLogicalDrives) 'get current drives
Dim eDrvs As IEnumerable(Of String)
Dim add_or_remove As Integer = 0 '0 = same number, 1 = removed, 2 = add
If cDrvs.Count = drvs.Count Then
'same number of drives - check that they are the same
eDrvs = drvs.Except(cDrvs)
ElseIf cDrvs.Count < drvs.Count Then
'drive(s) removed
eDrvs = drvs.Except(cDrvs)
add_or_remove = 1
Debug.WriteLine("R")
ElseIf cDrvs.Count > drvs.Count Then
'new drive(s)
eDrvs = cDrvs.Except(drvs)
add_or_remove = 2
Debug.WriteLine("A")
End If
For Each d As String In eDrvs
Debug.WriteLine(d)
Next
drvs = cDrvs 'set list of current drives
End Sub
Upvotes: 0
Reputation: 750
One solution can be WMI, especially the
Computer System Hardware Classes
Upvotes: 0
Reputation: 19618
Try this: http://www.dotnetthoughts.net/2009/02/13/how-to-detect-usb-insertion-and-removal-in-vbnet/
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
Upvotes: 6