Original: https://blog.csdn.net/liang19890820/article/details/50589404
Briefly
Through the understanding of the previous section, we can see that there are many ways of process communication. Today, we will share how to use the Windows message mechanism to communicate between different processes.
Effect
send messages
Custom Types and Receive Forms
Contains the required libraries, defines custom types to send, form headers for received messages. The custom type can handle the case of too many messages, and the distinction between messages can be removed if not needed.
#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";
- 1
- 2
- 3
- 4
- 5
- 6
- 7
send data
Click the button to send the message. The do{...}while inside is used to ignore this window, of course, it can also accept its own messages.
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));
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
receive message
set title
This step is very important and must be consistent with the c_strTitle of the previous step, otherwise the form will not be found. The custom type CUSTOM_TYPE must also be consistent for filtering.
setWindowTitle("ReceiveMessage");
- 1
Override nativeEvent
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);
}