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

来源:互联网 发布:cnzz 阿里云备案 编辑:程序博客网 时间:2024/03/28 16:44

转自: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); }

效果