QT下windows API 查找进程发送消息

转自 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>(&copydata));
    }
}

接收消息

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);
}

 

转载于:https://my.oschina.net/hanxiaodong/blog/1537821

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值