转自:http://hi.baidu.com/cyclone/blog/item/5c9382020cc2d1004bfb51bb.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
简单的对话框类,很简单(注意,用到了winEvent)
#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; unsigned long m_msgId; }; #endif // DIALOG_H
dialog.cpp
这是问题的重点
- g_count 放入共享段的全局变量
- 注意,MSVC 和 MinGW 二者共享段的代码不同
- m_msgId 注册的Windows消息,用来通知其他进程
#include <windows.h> #include <QtGui/QLabel> #include <QtGui/QHBoxLayout> #include "dialog.h" #ifdef Q_CC_MSVC #pragma data_seg("MyShared") #pragma comment(linker, "/Section:MyShared,RWS") #pragma comment(lib, "user32.lib") long g_count = 0; #pragma data_seg() #endif #ifdef Q_CC_GNU __attribute__((section ("MySHARED"), shared)) long g_count= 0; #endif Dialog::Dialog(QWidget *parent) : QDialog(parent),m_label(new QLabel) { QHBoxLayout * box = new QHBoxLayout(this); box->addWidget(m_label); setLayout(box); m_msgId = ::RegisterWindowMessageW(L"dbzhang-message-Qt4"); ::InterlockedExchangeAdd(&g_count, 1); ::PostMessageW(HWND_BROADCAST, m_msgId, 0, 0); m_label->setText(QString("Number of instances %1").arg(g_count)); } Dialog::~Dialog() { ::InterlockedExchangeAdd(&g_count, -1); ::PostMessageW(HWND_BROADCAST, m_msgId, 0, 0); } bool Dialog::winEvent(MSG *message, long *result) { if (message->message == m_msgId) { m_label->setText(QString("Number of instances %1").arg(g_count)); } return QDialog::winEvent(message, result); }
结果