我希望在我的应用程序中检测USB驱动器是否已插入或拔出。
我已经搜索了很多关于它的内容,并且实际上找到了很多答案,但没有一个完全符合我的想法。我找到一个完美的工作,并在插入或插入驱动器时发出消息,但使用 WndProc ,这是一个非常漫长的过程,特别难以理解对我没有任何了解但是这不是主要问题。我使用 WndProc 创建的主要问题是它无法执行我想要执行的某些功能,而 WMI 可以执行这些操作。我还找到了 WMI 解决方案,该解决方案可以在驱动器插入时检测到驱动器,但 无法检测到设备何时插入 em> 这对我的程序非常重要。我找到了另一种解决方案似乎有效,但它是在C#代码中,我试图将其转换为VB.Net但当我进入C#代码的代码行4时未能这样做(我将在后面的问题中添加)下文)。
指向部分帮助我的解决方案的链接:
- WndProc - www.vbforfree.com
检测到插入的驱动器并完美地插入事件。
- WMI Solution Vb.Net - www.vb-tips.com
在插入驱动器但无法检测到驱动器是否已拔出时,可以正常工作。
- WMI Solution 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();
答案 0 :(得分:2)
我找到了解决方案:)
参考文献
- 配置已更改(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