我希望在我的应用程序中检测USB驱动器是否已插入或已拔出。
我在谷歌上搜索了很多关于它的信息,实际上找到了很多答案,但没有一个答案能达到我想要的效果。我找到了一个非常有效的答案,当驱动器插入或拔出时会发出消息,但它使用WndProc,这是一个非常长的过程,对于我来说很难理解,因为我对它一无所知,但这不是主要问题。我使用WndProc创建的主要问题是它无法执行我想要执行的某些功能,而WMI可以执行这些功能。我还发现了WMI解决方案,它可以在驱动器插入时检测驱动器,但它无法检测设备何时插入,这对我的程序非常重要。我找到了另一个似乎有效的解决方案,但它是在C#代码中,我试图将其转换为VB.Net,但当我进入C#代码的第4行时失败了(我稍后将在下面的问题中添加)。
部分帮助我的解决方案链接:
- WndProc-www.vbforfree.com
完美检测驱动器插入和拔出事件
- WMI解决方案Vb.Net-www.Vb-tips.com
当驱动器插入时工作正常,但无法检测驱动器是否已插入
- WMI解决方案C#-stackoverflow.com
似乎可以工作,但未能将其转换为Vb.Net
我认为可能工作的C#代码:
using System.Management;
ManagementEventWatcher watcher = new ManagementEventWatcher();
WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2");
//I am stuck from the line below this
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Query = query;
watcher.Start();
watcher.WaitForNextEvent();
我找到了解决方案:)
Ref。
Win32_VolumeChangeEvent类
- 配置已更改(1)
- 设备到达(2)
- 设备拆卸(3)
- 对接(4)
代码:
Imports System.Management Imports Microsoft.Win32 Public Class Form1 Dim WithEvents pluggedInWatcher As ManagementEventWatcher Dim WithEvents pluggedOutWatcher As ManagementEventWatcher Dim pluggedInQuery As WqlEventQuery Dim pluggedOutQuery As WqlEventQuery Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Try pluggedInQuery = New WqlEventQuery pluggedInQuery.QueryString = "SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2" pluggedInWatcher = New ManagementEventWatcher(pluggedInQuery) pluggedInWatcher.Start() pluggedOutQuery = New WqlEventQuery pluggedOutQuery.QueryString = "SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 3" pluggedOutWatcher = New ManagementEventWatcher(pluggedOutQuery) pluggedOutWatcher.Start() Catch ex As Exception MsgBox(ex.Message) End Try End Sub Private Sub pluggedInWatcher_EventArrived(sender As Object, e As EventArrivedEventArgs) Handles pluggedInWatcher.EventArrived MsgBox("Plugged In") End Sub Private Sub pluggedOutWatcher_EventArrived(sender As Object, e As EventArrivedEventArgs) Handles pluggedOutWatcher.EventArrived MsgBox("Plugged Out") End Sub End Class