qt 单例程序
1.http://qt.nokia.com的网站把QtSingleApplication 的源代码qtsingleapplication-2.6_1-opensource.zip 下载下来,然后解压缩。假 设解压缩到路径: E:\qtsingleapplication-2.6_1-opensource
2.
编写程序代码如下:
#include <QLabel>
#include <QWidget>
#include <QMessageBox>
#include <QApplication>
#include "E:\qtsingleapplication-2.6_1-opensource\src\QtSingleApplication"
int main(int argc,char* argv[])
{
QtSingleApplication app(argc,argv);
if (app.isRunning())
{
QMessageBox::information(0, "test",
"An instance has already been running.");
return 0;
}
QLabel label("<h2>test</h2>");
label.show();
return app.exec();
}
3.
编译
qmake –project
qmake
nmake
第二种方案:
QApplicationapp(argc,argv);
HANDLEhMutex=CreateMutex(NULL,true,QString("['{EFEB2EF6-F8E0-AE44-BABE-1BBEF2C7FD56}']").toStdWString().c_str());
if(GetLastError()==ERROR_ALREADY_EXISTS)
{
CloseHandle(hMutex);
QMessageBox::information(NULL,QObject::tr("error"),QObject::tr("一个实例已经在运行,请关闭后重新打开"),"OK");
app.exit(1);
return1;
}