C# 通过WMI检测USB热插拔
作者:互联网
需要添加引用System.Management.dll
static void Main(string[] args)
{
var watchConnect = new ManagementEventWatcher(new WqlEventQuery
{
EventClassName = "__InstanceCreationEvent",
Condition = "TargetInstance ISA 'Win32_USBControllerDevice'",
WithinInterval = new TimeSpan(0, 0, 2)
});
watchConnect.EventArrived += new EventArrivedEventHandler(USBDevice_Connected);
watchConnect.Start();
var watchDelete = new ManagementEventWatcher(new WqlEventQuery
{
EventClassName = "__InstanceDeletionEvent",
Condition = "TargetInstance ISA 'Win32_USBControllerDevice'",
WithinInterval = new TimeSpan(0, 0, 2)
});
watchDelete.EventArrived += new EventArrivedEventHandler(USBDevice_Disconnected);
watchDelete.Start();
Console.ReadLine();
}
private static void USBDevice_Connected(object sender, EventArrivedEventArgs e)
{
Console.WriteLine("新的USB已连接.");
}
private static void USBDevice_Disconnected(object sender, EventArrivedEventArgs e)
{
Console.WriteLine("某个USB已断开.");
}
标签:watchDelete,Console,USB,C#,热插拔,static,new,USBDevice 来源: https://www.cnblogs.com/wtla/p/14219841.html