Qt 与外部exe进程间通信-基于操作系统的消息传递

步骤:

进程A 通过WindowAPI找到需要传递信息的窗口。

然后通过windowAPI发送自定义的消息(其实本质上还是window操作系统定义的消息结构,只不过其中有个字段的值被设置成了自己特有的值:const ULONG_PTR CUSTOM_TYPE_SEND_WEBVIEWER = 10007;)这样在发送带有需要传递的信息。

进程B通过Qt已经实现的 nativeEvent()函数来捕获window系统发送过来的消息。

然后通过对消息的筛选(即之前自定义消息中的特定字段的值的判断ULONG_PTR CUSTOM_TYPE_SEND_WEBVIEWER = 10007来确实是否是自己想要的信息),获取到想要信息后,就直接对信息处理,完成想要的功能。

进程A:

#ifdef Q_OS_WIN
#pragma comment(lib, "user32.lib")
#include <qt_windows.h>
#include "windows.h"
#endif
const ULONG_PTR CUSTOM_TYPE_SEND_WEBVIEWER = 10007;



//
		char strId[256];
		q2s(qstrId).copy(strId , qstrId.size(),0);
		strId[qstrId.size()]= '\0';
//调用window.h种的api来寻找标题为“RKWebViewModel”的窗口。
		HWND hwnd = NULL ;
		QString qstrReceiveName =QString::fromLocal8Bit("RKWebViewModel");
		LPWSTR path = (LPWSTR)qstrReceiveName.utf16();
		hwnd = ::FindWindowW(NULL ,path);
//判断找到的句柄是否为窗口,如果是就通过window的消息COPYDATASTRUCT结构体来实现信息与数据的封装
		if (::IsWindow(hwnd))
		{
			COPYDATASTRUCT  copydata ;
			memset(&copydata , 0 ,sizeof(COPYDATASTRUCT));
			copydata.dwData = CUSTOM_TYPE_SEND_WEBVIEWER;  // 用户定义数据
			copydata.lpData = strId ;  // 指向数据的指针
			copydata.cbData = qstrId.size();    //数据大小
//winApi发送信息(通过操作系统的消息传递机制)
            ::SendMessage(hwnd, WM_COPYDATA, reinterpret_cast<WPARAM>((HWND)(this->winId())), reinterpret_cast<LPARAM>(&copydata));
			//ProMessageHandleC::sendMessageByCameraInfo((HWND)(this->winId()), c_strTitle, pszData, sizeof(stuDeviceInfo));
		}

 

进程B:

#ifdef Q_OS_WIN
#pragma comment(lib, "user32.lib")
#include <qt_windows.h>
#endif
const ULONG_PTR CUSTOM_TYPE_SEND_WEBVIEWER = 10007;

//bool winEvent(MSG * message, long * result)
bool nativeEvent(const QByteArray &eventType, void *message, long *result)
{
	MSG *param = static_cast<MSG *>(message);

	switch (param->message)
	{
	case WM_COPYDATA:
	{
		COPYDATASTRUCT *cds = reinterpret_cast<COPYDATASTRUCT*>(param->lParam);
		if (cds->dwData == CUSTOM_TYPE_SEND_WEBVIEWER)
		{
			char strId[256];
			memcpy(strId, reinterpret_cast<char*>(cds->lpData),cds->cbData);
			
			qDebug() << strId <<endl;
			if (!QString(strId).isEmpty())
			{
				m_pWebEngineView->setFloodId(QString(strId));
			}
			return true;
		}
	}
	
    }

	return QWidget::nativeEvent(eventType, message, result);
	//return QWidget::winEvent(message, result);
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值