Qt使用WM_COPYDATA消息进行进程通信

有时候我们需要使用qt接受别的进程发送过来的消息,那边进程发送使用WM_COPYDATA,qt这边如何接收到呢?
很简单:

bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
    MSG*msg = (MSG*)message;
    switch(msg->message)
    {
    case WM_COPYDATA:
         //do something... 
    }
    //其他交给qt处理
    return QWidget::nativeEvent(eventType, message, result);
}

下面转自:https://blog.csdn.net/weixin_41619400/article/details/105807525
之前利用nativeEvent 截获来着系统的消息。发现有 WM_COPYDATA 消息接收不到的问题。(在操作下拉框之后,多么奇怪的bug),后来查找资料,有人说 数据处理太多,处理不及时,导致截获消息失败

win32 WM_COPYDATA 消息结构体

typedef struct tagCOPYDATASTRUCT {
    ULONG_PTR dwData; //用户定义数据
    DWORD cbData; //用户定义数据的长度
    __field_bcount(cbData) PVOID lpData; //指向用户定义数据的指针
} COPYDATASTRUCT, *PCOPYDATASTRUCT;

修改主窗口代码:重写nativeEventFilter 函数

class ***: public QMainWindow,public QAbstractNativeEventFilter
{
	Q_OBJECT
public:
	explicit ***(QWidget *parent = 0);
	~***();
	virtual bool nativeEventFilter(const QByteArray &eventType, void *message, long *) Q_DECL_OVERRIDE;

在xxx.cpp中重写

bool xxx::nativeEventFilter(const QByteArray &eventType, void *message, long *result)
{
	if (eventType == "windows_generic_MSG") //windows平台
	{
		MSG* msg = reinterpret_cast<MSG*>(message); 
		if (msg->message == WM_APPCOMMAND || msg->message == WM_COPYDATA)//消息类型
		{
			COPYDATASTRUCT *data = reinterpret_cast<COPYDATASTRUCT*>(msg->lParam);
			QTextCodec *codec = QTextCodec::codecForName("UTF-8");
 
			QTextCodec::setCodecForLocale(codec);
			QString recevice = QString::fromLocal8Bit((char *)(data->lpData)).toUtf8();
			//QMessageBox::information(NULL, QStringLiteral("WM_COPYDATA"), recevice);
			if (recevice.contains("Command_Browserjoining"))
			{
			    //事件处理
				return true;//消息不再进行传递,不再处理
			}
 
		}
	}
	return QWidget::nativeEvent(eventType, message, result);//交给Qt处理
}

之后 在main 函数中 给主窗口添加 事件过滤

QApplication app(argc, argv);
 
	QSharedMemory shared("NewVision");    
	if (shared.isAttached())
	{
		shared.detach();
	}
	if (!shared.create(1024))
    {
        return ;
    }
	*** window;
	app.installNativeEventFilter(&***);//事件过滤
 
    ***.show();
    app.exec();
原文地址:https://www.cnblogs.com/ruandahua/p/14074479.html