我使用此处Detecting USB drive insertion and removal using windows service and c#这样的代码来检测何时插入/移除了USB设备。
但是,当用户“弹出”设备并使其插入电源时,我根本没有收到任何通知。 当然,当我尝试访问这种驱动器时,它将失败。
是否可以使用其他WMI事件来获取有关此情况的通知?
@Jimi发布的链接使我更进一步(BIG)。
public void AddWMIWatcher() {
WqlEventQuery query = new WqlEventQuery();
ManagementScope scope = new ManagementScope("root\\CIMV2");
query.EventClassName = "__InstanceOperationEvent";
query.WithinInterval = new TimeSpan(0, 0, 3);
query.Condition = @"TargetInstance ISA 'Win32_DiskDrive' ";
ManagementEventWatcher watcher = new ManagementEventWatcher(scope, query);
watcher.EventArrived += Watcher_EventArrived;
watcher.Query = query;
watcher.Start();
}
private void Watcher_EventArrived(object sender, EventArrivedEventArgs e) {
ManagementBaseObject baseObject = e.NewEvent;
if(baseObject.ClassPath.ClassName.Equals("__InstanceCreationEvent")) {
Console.WriteLine("A drive was connected");
}
else if(baseObject.ClassPath.ClassName.Equals("__InstanceDeletionEvent")) {
Console.WriteLine("A drive was removed");
}
else if(baseObject.ClassPath.ClassName.Equals("__InstanceModificationEvent")) {
Console.WriteLine("A drive was changed");
//that is what I'm looking for
}
我得到一个__InstanceModificationEvent-我唯一需要了解的是如何从该事件中删除受影响的驱动器(字母)。