c++ - 如何在 Windows 7/8/10 中从 Qt 绑定连接/断开 USB 设备事件
问题描述
我需要执行以下操作。我有 USB-UART 转换器,当它插入时,它被识别为串行端口。我需要读取此串行端口的名称并将其添加到组合框中,用户可以在其中选择并打开以进行数据传输。
在 Qt 中获得可用的串行端口不是问题。但我只想在插入或移除设备时这样做。我在 Linux 中通过监听相应的 DBus 信号来做到这一点。Windows中有类似的东西吗?我确切需要的是每次连接或断开新的串行端口时从系统接收我的应用程序中的消息。
我找到了一些 .NET C# 的解决方案,但不知道如何在 Qt 中重现它们。谢谢!
解决方案
感谢@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!
推荐阅读
- javascript - 仅从对象数组 gcloud 数据存储中获取选定对象
- android - onScroll RecyclerView Adapter 中的定时器值变化
- .net - 如何以在 .NET 中发布 Web 应用程序的方式发布 Windows 应用程序?
- python - 带有正则表达式的 p4 文件日志
- android - 使用 NDK 为 Android 构建 capicxx-someip-runtime
- javascript - 本机 Javascript - 如果语句不起作用,则具有 else 属性
- ios - 如何使用“使用应用程序时”定位服务获取地理通知
- latex - 用于 LaTeX 的 pgf tikz 如何将 x 和 y 坐标与节点一起使用
- java - 在 Java 中分配给字符串缓冲区的内存没有被清除
- java - 将字符连接到字符串数组时获取“null”