Qt 进程间通讯学习(windows消息WM_COPYDATA)

转自:http://hi.baidu.com/cyclone/blog/item/d77a8618446dacbb4aedbcee.html


例子

main.cpp

很简单

#include <QtGui/QApplication> 
#include "dialog.h" 
int main(int argc, char *argv[]) 
{ 
    QApplication a(argc, argv); 
    Dialog w; 
    w.show(); 
    
    return a.exec(); 
}

dialog.h

同样很简单,只不过启用winEvevt

#ifndef DIALOG_H 
#define DIALOG_H 
#include <QtGui/QDialog> 
class QLabel; 
class Dialog : public QDialog 
{ 
    Q_OBJECT  
public: 
    Dialog(QWidget *parent = 0); 
    ~Dialog(); 
protected: 
    bool winEvent(MSG *message, long *result); 
private: 
    QLabel * m_label; }; 
#endif // DIALOG_H

dialog.cpp

代码的重点

  • 窗口初始化时查找 "Dbzhang800-Recv" 窗体是否存在
    • 若存在,则发送数据
    • 若不存在,则自己作为接受窗体,等待数据
#include <windows.h> 
#include <QtGui/QHBoxLayout> 
#include <QtGui/QLabel> 
#include "dialog.h"
 
#ifdef Q_CC_MSVC 
#pragma comment(lib, "user32.lib") 
#endif 
 
Dialog::Dialog(QWidget *parent) 
    : QDialog(parent), m_label(new QLabel) 
{ 
    QHBoxLayout * box = new QHBoxLayout(this); 
    box->addWidget(m_label); 
    setLayout(box); 

    HWND hWnd = ::FindWindowW(NULL, L"Dbzhang800-Recv"); 
    if (hWnd != NULL) { 
        setWindowTitle("Dbzhang800-Send"); 
        QString str("Message from dbzhang800-send"); 
        COPYDATASTRUCT cpd; 
        cpd.dwData = 0; 
        cpd.cbData = str.length()+1; 
        cpd.lpData = str.toAscii().data(); 
        ::SendMessageW(hWnd, WM_COPYDATA, NULL, (LPARAM)&cpd); 
        m_label->setText("Message has been sent."); 
    } else { 
        setWindowTitle("Dbzhang800-Recv"); 
        m_label->setText("Ready..."); 
    } 
} 
 
Dialog::~Dialog() 
{  
} 

bool Dialog::winEvent(MSG *message, long *result) 
{ 
    if (message->message == WM_COPYDATA){ 
        COPYDATASTRUCT * p = reinterpret_cast<COPYDATASTRUCT*>(message->lParam); 
        m_label->setText(static_cast<char*>(p->lpData)); 
    } 
    return QDialog::winEvent(message, result); 
}

效果




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值