我正在尝试检测RNDIS兼容设备何时插入或拔出(通过USB)。
我认为以下设置将在RNDIS设备被插入或拔出时触发事件:
private System.ComponentModel.BackgroundWorker bgwDriveDetector;
public SomeConstructor()
{
this.bgwDriveDetector = new System.ComponentModel.BackgroundWorker();
this.bgwDriveDetector.DoWork += bgwDriveDetector_DoWork;
this.bgwDriveDetector.RunWorkerAsync();
}
void bgwDriveDetector_DoWork(object sender, DoWorkEventArgs e)
{
var detectQuery = new WqlEventQuery("SELECT * FROM _InstanceModificationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_NetworkAdapter'");
var detectWatcher = new ManagementEventWatcher(detectQuery);
detectWatcher.EventArrived += DeviceDetectedtedEvent;
detectWatcher.Start();
}
// Will run when device detected
private void DeviceDetectedtedEvent(object sender, EventArrivedEventArgs e)
{
ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
var status = (ushort)instance.GetPropertyValue("NetConnectionStatus");
switch (status)
{
case 2:
Console.WriteLine("Connected");
break;
case 7:
Console.WriteLine("Disconnected");
break;
}
…
}
从现在开始,我遇到以下问题:
也许我应该使用“ Win32_USBController”而不是“ Win32_NetworkAdapter”。
事件似乎可以正确触发,并且不那么不稳定。不知道为什么吗??
然后,我可以通过供应商ID(VID)隔离设备,但这不会告诉我哪个设备实例正在插入或拔出。