[PyQt5] 窗口接收WM_COPY消息

#本程序是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 MSG

WM_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;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值