Qt 進程間通訊學習(windows消息WM_COPYDATA)

接前面繼續 Qt 下在windows下的進程間通訊。本文學習 WM_COPYDATA 消息的使用

例子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_Hdialog.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); 
}效果
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章