驾驶信观察者

时间:2011-02-06 11:08:26

标签: c# .net vb.net

而不是FileSystemWachter类,我正在查找类似于弹出新驱动器号时的内容。例如,当连接USB磁盘或插入SD卡等时,您将获得一个新的驱动器号。我想在我的应用程序中发生这样的事件。

你可以使用FileSystemWatcher类,还是有特定的东西?

任何示例或建议?

3 个答案:

答案 0 :(得分:6)

试试这个: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

答案 1 :(得分:0)

一个解决方案可以是WMI,尤其是

Computer System Hardware Classes

答案 2 :(得分: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