我正在开发一个应该检测连接到计算机的 USB 设备的应用程序。在网上搜索得到如下代码:
Public Class Form1
Private Const WM_DEVICECHANGE As Integer = &H219
Private Const DBT_DEVICEARRIVAL As Integer = 32768
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
If m.Msg = WM_DEVICECHANGE Then
If m.WParam = DBT_DEVICEARRIVAL Then
MessageBox.Show("Removable Drive Detected")
End If
End If
MyBase.WndProc(m)
End Sub
End Class
这段代码适合我。
但问题是,如果先连接USB设备,再启动应用程序,则无法检测到USB设备。
最佳答案
修复起来很简单,只需添加一个计时器,双击它,输入该代码,然后返回到您的启动表单,双击它,然后输入
Timer1.start
这将根据您的计时器滴答率在几秒钟内检查一次
10000 = 10 seconds
60000 = 60 seconds
3600000 = 1 hour
7200000 = 2 hours
43200000 = half a day
86400000 = 1 day
但是仍然存在一个问题,消息框会一遍又一遍地出现,并且您将有多层消息框,因此请尝试将计时器中的代码更改为:
Public Class Form1
If label1.text = "0" then
Private Const WM_DEVICECHANGE As Integer = &H219
Private Const DBT_DEVICEARRIVAL As Integer = 32768
Label1.text = "1"
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
If m.Msg = WM_DEVICECHANGE Then
If m.WParam = DBT_DEVICEARRIVAL Then
msgbox("Removable Drive Detected", msgboxstyle.OkOnly
if vbok then label1.text = "0"
End If
End If
MyBase.WndProc(m)
End Sub
End Class
您需要添加一个标签,如果您不想看到它,只需点击它转到属性(右侧)和
disable visible
关于vb.net - 无法检测到 USB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23225170/