我正在编写一个 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 的引用
关于.net - 如何在没有窗口句柄的情况下使用 RegisterDeviceNotification?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10022794/