首页 > 解决方案 > 如何在 Windows 7/8/10 中从 Qt 绑定连接/断开 USB 设备事件

问题描述

我需要执行以下操作。我有 USB-UART 转换器,当它插入时,它被识别为串行端口。我需要读取此串行端口的名称并将其添加到组合框中,用户可以在其中选择并打开以进行数据传输。

在 Qt 中获得可用的串行端口不是问题。但我只想在插入或移除设备时这样做。我在 Linux 中通过监听相应的 DBus 信号来做到这一点。Windows中有类似的东西吗?我确切需要的是每次连接或断开新的串行端口时从系统接收我的应用程序中的消息。

我找到了一些 .NET C# 的解决方案,但不知道如何在 Qt 中重现它们。谢谢!

标签: c++windowsqtserial-portusb

解决方案


感谢@kunif,我找到了解决方案。因此,要收听 Windows 消息,您需要通过继承QAbstractNativeEventFilter来添加自己的EventFilter ,如下所示:

#include <QAbstractNativeEventFilter>
#include <QObject>

class DeviceEventFilter : public QObject, public QAbstractNativeEventFilter
{
    Q_OBJECT

public:
    DeviceEventFilter();
    bool nativeEventFilter(const QByteArray &eventType, void *message, long *) override;

signals:
    void serialDeviceChanged();
};

并过滤您需要WM_DEVICECHANGE的消息:

#include <windows.h>
#include <dbt.h>

bool DeviceEventFilter::nativeEventFilter(const QByteArray &eventType, void *message, long *) {
    if (eventType == "windows_generic_MSG") {
        MSG *msg = static_cast<MSG *>(message);

        if (msg->message == WM_DEVICECHANGE) {
            if (msg->wParam == DBT_DEVICEARRIVAL || msg->wParam == DBT_DEVICEREMOVECOMPLETE) {
                // connect to this signal to reread available ports or devices etc
                emit serialDeviceChanged();        
            }
        }
    }
    return false;
}

在您的代码中的某个地方,您可以访问DeviceEventFilter对象添加以下行:

qApp->installNativeEventFilter(&devEventFilterObj);

或在main.cpp

QApplication app(argc, argv);
app.installNativeEventFilter(&devEventFilterObj);

感谢@kunif


推荐阅读