1. 头文件:
#include <windows.h>
#include <tlhelp32.h>
2. 发送方:
void sendMessage()
{
// 根据窗口名称查找窗口句柄
HWND hWnd = ::FindWindowA(("myWindowsName"), NULL);
if (hWnd == nullptr) {
return;
}
// 组装copydata信息
std::string param = QString("UID=0\r\nCommand=ChangeCode\r\n").toStdString();
COPYDATASTRUCT data;
data.dwData = 0;
data.cbData = param.length();
data.lpData = ¶m[0];
// 发送消息
::SendMessage(hWnd, WM_COPYDATA, (WPARAM)0, (LPARAM)&data);
}
3. 接收方:?
bool nativeEvent(const QByteArray &eventType, void *message, long *result);//接收消息
bool xxxWidget::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
if (eventType == "windows_generic_MSG")
{
MSG* msg = reinterpret_cast<MSG*>(message);
if(msg->message == WM_COPYDATA)
{
COPYDATASTRUCT *data = reinterpret_cast<COPYDATASTRUCT*>(msg->lParam);
QTextCodec *gbk = QTextCodec::codecForName("GB18030");
QString recevice = gbk->toUnicode((char *)(data->lpData));
// 业务1
if(recevice.contains("Command=openNewTab")) {
//TODO 业务1处理
return true;
} else if(recevice.contains("Command=close")) {
// TODO 业务2处理
return true;
}
m_wnd = reinterpret_cast<HWND>(msg->wParam);
}
}
return QWidget::nativeEvent(eventType, message, result);
}
|