转自 https://yq.aliyun.com/articles/24435
发送消息
#ifdef Q_OS_WIN
#pragma comment(lib, "user32.lib")
#include <qt_windows.h>
#endif
const ULONG_PTR CUSTOM_TYPE = 10000;
const QString c_strTitle = "ReceiveMessage";
void onSendMessage()
{
HWND hwnd = NULL;
//do
//{
LPWSTR path = (LPWSTR)c_strTitle.utf16(); //path = L"SendMessage"
hwnd = ::FindWindowW(NULL, path);
//} while (hwnd == (HWND)effectiveWinId()); // 忽略自己
if (::IsWindow(hwnd))
{
QString filename = QStringLiteral("进程通信-Windows消息");
QByteArray data = filename.toUtf8();
COPYDATASTRUCT copydata;
copydata.dwData = CUSTOM_TYPE; // 用户定义数据
copydata.lpData = data.data(); //数据大小
copydata.cbData = data.size(); // 指向数据的指针
HWND sender = (HWND)effectiveWinId();
::SendMessage(hwnd, WM_COPYDATA, reinterpret_cast<WPARAM>(sender), reinterpret_cast<LPARAM>(©data));
}
}
接收消息
setWindowTitle("ReceiveMessage");
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)
{
QString strMessage = QString::fromUtf8(reinterpret_cast<char*>(cds->lpData), cds->cbData);
QMessageBox::information(this, QStringLiteral("提示"), strMessage);
*result = 1;
return true;
}
}
}
return QWidget::nativeEvent(eventType, message, result);
}