我正在尝试使用 WinForm 桌面 C# 应用程序检测 USB 设备插入和删除:
public Form1()
{
InitializeComponent();
USB();
}
然后:
private void USB()
{
WqlEventQuery weqQuery = new WqlEventQuery();
weqQuery.EventClassName = "__InstanceOperationEvent";
weqQuery.WithinInterval = new TimeSpan(0, 0, 3);
weqQuery.Condition = @"TargetInstance ISA 'Win32_DiskDrive'";
var m_mewWatcher = new ManagementEventWatcher(weqQuery);
m_mewWatcher.EventArrived += new EventArrivedEventHandler(m_mewWatcher_EventArrived);
m_mewWatcher.Start();
}
和:
static void m_mewWatcher_EventArrived(object sender, EventArrivedEventArgs e)
{
bool bUSBEvent = false;
foreach (PropertyData pdData in e.NewEvent.Properties)
{
ManagementBaseObject mbo = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value;
// ManagementBaseObject mbo = (ManagementBaseObject)pdData.Value;
if (mbo != null)
{
foreach (PropertyData pdDataSub in mbo.Properties)
{
if (pdDataSub.Name == "InterfaceType" && pdDataSub.Value.ToString() == "USB")
{
bUSBEvent = true;
break;
}
}
if (bUSBEvent)
{
if (e.NewEvent.ClassPath.ClassName == "__InstanceCreationEvent")
{
MessageBox.Show ("USB was plugged in");
}
else if (e.NewEvent.ClassPath.ClassName == "__InstanceDeletionEvent")
{
MessageBox.Show("USB was plugged out");
}
}
}
}
}
ManagementBaseObject mbo = (ManagementBaseObject)pdData.Value;
但是当检测到 USB 更改时我遇到了异常 :
Controller.exe 中出现“System.InvalidCastException”类型的异常,但未在用户代码中处理
附加信息:无法将“System.UInt64”类型的对象转换为“System.Management.ManagementBaseObject”类型。
编辑:
using System;
using System.Windows.Forms;
using System.Management;
namespace test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
WqlEventQuery query = new WqlEventQuery()
{
EventClassName = "__InstanceOperationEvent",
WithinInterval = new TimeSpan(0, 0, 3),
Condition = @"TargetInstance ISA 'Win32_DiskDrive'"
};
using (ManagementEventWatcher MOWatcher = new ManagementEventWatcher(query))
{
MOWatcher.EventArrived += new EventArrivedEventHandler(DeviceInsertedEvent);
MOWatcher.Start();
}
}
private void DeviceInsertedEvent(object sender, EventArrivedEventArgs e)
{
using (ManagementBaseObject MOBbase = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)
{
bool DriveArrival = false;
string EventMessage = string.Empty;
string oInterfaceType = MOBbase.Properties["InterfaceType"]?.Value.ToString();
if (e.NewEvent.ClassPath.ClassName.Equals("__InstanceDeletionEvent"))
{
DriveArrival = false;
EventMessage = oInterfaceType + " Drive removed";
}
else
{
DriveArrival = true;
EventMessage = oInterfaceType + " Drive inserted";
}
EventMessage += ": " + MOBbase.Properties["Caption"]?.Value.ToString();
this.BeginInvoke((MethodInvoker)delegate { this.UpdateUI(DriveArrival, EventMessage); });
}
}
private void UpdateUI(bool IsDriveInserted, string message)
{
if (IsDriveInserted)
{
this.label1.Text = message;
}
else
{
this.label1.Text = message;
}
}
}
}