如何检测插入PC VB的新设备?

时间:2018-02-12 00:30:11

标签: .net vb.net loops device

我想知道当设备连接到电脑时是否可以读取(如果是USB存储设备或其他设备则不重要)。我尝试了一下,但我没有找到任何东西。有人可以告诉我该怎么做?我想创建一些可以理解插入设备的东西(可能在后台有一个循环),如果插入它,它会执行特定的操作。我使用的是VisualBasic .NET 4.5.2(我可以使用我想要的.NET版本)。

1 个答案:

答案 0 :(得分:1)

当存储设备插入计算机时,您可以使用WMI引发事件

'set a reference to system management 
 Imports System.Management
 Public Class Form1
     Private WithEvents w As ManagementEventWatcher
     Private q As WqlEventQuery
     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
       q = New WqlEventQuery("Select * from Win32_DeviceChangeEvent")
       w = New ManagementEventWatcher(q)
       w.Start()
    End Sub
   Private Sub w_EventArrived(ByVal sender As Object, ByVal e As System.Management.EventArrivedEventArgs) Handles w.EventArrived
       MessageBox.Show("Device Event", e.Context.ToString)
   End Sub
   Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        w.Stop()
    End Sub
 End Class

http://vb-tips.com/DeviceNotifyWMI.aspx