.net - 如何在没有窗口句柄的情况下使用 RegisterDeviceNotification?

我正在编写一个 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 的引用

https://stackoverflow.com/questions/10022794/

相关文章:

python - 在横向模式下使用 xhtml2pdf 生成 PDF

php - PDOStatement::fetch() 说明

xslt-2.0 - XSL 中的显式类型变量

api - 如何使用 WSDL 格式的 Ideone API

visual-studio - 如何在 Visual Studio 2008 的左侧显示 "file

activex - 是否有 MsStkPrp.dll 的 x64 版本

.net - 将 salt/IV 与散列/密文连接/编码的标准?

asp.net - SSRS 报告缓慢加载第一份报告

assembly - ARM7TDMI(GameBoy Advance)上操作系统相关的操作和模式

snmp - SNMPv3 是否需要使用用户名/身份验证和社区字符串?