#本程序是python qt5 创建的窗口,拦截外部消息给窗口发送的WM_COPY消息并显示出来。一般是用来作为窗口之间的通讯机制之一。
python文件如下:qt5拦截消息
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow ,QTextEdit,QPushButton
import ctypes,array,struct
from ctypes.wintypes import MSGWM_COPY = 0X004A; #原始window消息全局定义def btn0_clicked():print("#button_0 clicked!")class COPYDATASTRUCT(ctypes.Structure):_fields_ = [('dwData', ctypes.wintypes.LPARAM),('cbData', ctypes.wintypes.DWORD),('lpData', ctypes.c_void_p)]
PCOPYDATASTRUCT = ctypes.POINTER(COPYDATASTRUCT)class MainWindow(QMainWindow):def nativeEvent(self, eventType, msg):msg_come = MSG.from_address(msg.__int__())#print("got msg_id:",msg_come.message);if msg_come.message == WM_COPY:#print("Recv copy message.")PCOPYDATASTRUCT = ctypes.POINTER(COPYDATASTRUCT)pCDS = ctypes.cast(msg_come.lParam, PCOPYDATASTRUCT)str=ctypes.string_at(pCDS.contents.lpData)print(str.decode('utf-8')) edit1.setPlainText(str.decode('utf-8'))return False,0 # 表示事件被处理return super().nativeEvent(eventType, msg) if __name__ == '__main__':app = QApplication([])wnd = MainWindow()wnd.setWindowTitle("#XCtrl#")btn0 = QPushButton("Button0", wnd)btn0.clicked.connect(btn0_clicked) edit1 = QTextEdit(wnd)edit1.setGeometry(0, 40, 200, 100)wnd.setGeometry(50, 50, 250, 250)wnd.show()app.exec_()
cpp端发送WM_COPY消息 :
void LogBox(char* str, int len)
{COPYDATASTRUCT cpd;cpd.cbData = len;cpd.lpData = (void*)str;//类名可以通过Spy++搜索对应窗口得到HWND hWndRcv = ::FindWindowA("Qt5152QWindowIcon", "#XCtrl#");if (hWndRcv){::SendMessage(hWndRcv, WM_COPYDATA, (WPARAM)len, (LPARAM)&cpd);}return;
}