接前面继续 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();
}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 <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);
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().da
::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);
}效果