2011-02-06 99 views
1

而不是FileSystemWachter類我看起來類似於當彈出一個新驅動器盤符時看起來類似的東西。例如,當連接一個USB磁盤或插入一個SD卡時,您將得到一個新的驅動器盤符。發生這種情況時,我希望在我的應用中有一個活動。驅動器盤查看器

你可以使用FileSystemWatcher類嗎?或者是否有特定的東西?

任何示例或建議?

+0

你希望你的應用程序響應它有多快? – 2011-02-06 11:21:37

+0

儘可能快:) – Marcel 2011-02-06 11:28:51

回答

5

嘗試這種情況: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 
+0

我看到這個,但比我不知道哪個驅動器號被添加。我只是現在插入了一個USB設備。 – Marcel 2011-02-06 11:29:40

+0

當WM_DEVICECHANGE是DBT_DEVICEARRIVAL類型時,它還將包含一個lParam對象,該對象應該包含一個可以獲取設備信息的結構。它將位於結構DEV_BROADCAST_HDR中。如果你用VB包裝它,你將能夠識別該設備。 http://msdn.microsoft.com/en-us/library/aa363246(v=vs.85).aspx – 2011-02-06 13:35:40

0

這裏是使用定時器的溶液。這不是特定於USB類型的設備。

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