我正在编写一个 DLL 库,该库使用 VB.NET 中的 winusb 连接到 USB 设备。
由于它是一个 DLL,所以我没有窗口,而且我的库的用户也可能没有窗口(例如命令行应用程序)。
我见过的检测设备连接和分离的示例都使用RegisterDeviceNotification
这需要一个窗口句柄来接收附加/分离消息。
如何在没有窗口来获取句柄的情况下直接将这些消息接收到函数中?
我最近发现了一个对于没有 GUI 的应用程序来说似乎比 RegisterDeviceNotification 更优雅的解决方案。
void onEventArrived(object sender, EventArrivedEventArgs e)
{
ManagementBaseObject _o = e.NewEvent["TargetInstance"] as ManagementBaseObject;
if (_o != null)
{
using (ManagementObject mo = new ManagementObject(_o["Dependent"].ToString()))
{
if (mo != null)
{
try
{
if (mo.GetPropertyValue("DeviceID").ToString() != string.Empty)
{
//connected
}
}
catch (ManagementException ex)
{
//disconnected
}
}
}
}
}
通过调用初始化此代码
System.Management.WqlEventQuery _q = new WqlEventQuery("__InstanceOperationEvent", "TargetInstance ISA 'Win32_USBControllerDevice' ");
_q.WithinInterval = TimeSpan.FromSeconds(1);
ManagementEventWatcher _w = new ManagementEventWatcher(_q);
_w.EventArrived += new EventArrivedEventHandler(onEventArrived);
_w.Start();
另请确保添加对 System.Management 的引用
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)