Qt中通过Windows消息进行监测串口的热插拔

1. QAbstractNativeEventFilter

对于此类的Qt官方解释为:
The QAbstractNativeEventFilter class provides an interface for receiving native events, such as MSG or XCB event structs. More…
这个抽象事件过滤类提供了一个接收本地事件的接口,类如Windows的MSG或者XCB…
所以,需要我们的类继承此类,并重写虚函数。形如:

class OwnerClass : public QMainWindow, public QAbstractNativeEventFilter{
	......
	bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) override;
	......
}

2.具体实现

bool OwnerClass::nativeEventFilter(const QByteArray & eventType, void * message, long * result)
{
	MSG* msg = reinterpret_cast(message);
	int msgType = msg->message;
	if (msgType == WM_DEVICECHANGE) {
		PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)msg->lParam;
		switch (msg->wParam) {
		case DBT_DEVICEARRIVAL:
			if (lpdb->dbch_devicetype == DBT_DEVTYP_PORT) {
				PDEV_BROADCAST_PORT lpdbv = (PDEV_BROADCAST_PORT)lpdb;
				QString port = QString::fromWCharArray(lpdbv->dbcp_name);//插入的串口名
				//emit open(port);//发送串口打开信号
			}
			break;
		case DBT_DEVICEREMOVECOMPLETE:
			if (lpdb->dbch_devicetype == DBT_DEVTYP_PORT) {
				PDEV_BROADCAST_PORT lpdbv = (PDEV_BROADCAST_PORT)lpdb;
				QString port = QString::fromWCharArray(lpdbv->dbcp_name);//拔出的串口名
				//emit close(port);//发送串口关闭信号
			}
			break;
		case DBT_DEVNODES_CHANGED:
			break;
		default:
			break;
		}
	}
	return QWidget::nativeEvent(eventType, message, result);
}

3 注册

在main函数中注册过滤器,形如下图所示:
Qt中通过Windows消息进行监测串口的热插拔_第1张图片

你可能感兴趣的:(Qt)