qt程序单例运行
bool CheckOne()
{
// 创建互斥量
HANDLE m_hMutex = CreateMutex(NULL, FALSE, L"软件名字" );
// 检查错误代码
if (GetLastError() == ERROR_ALREADY_EXISTS) {
// 如果已有互斥量存在则释放句柄并复位互斥量
CloseHandle(m_hMutex);
m_hMutex = NULL;
// 程序退出
return false;
}
else
return true;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
if(!CheckOne())
{
return 0;
}
QtHttpServer w;
w.show();
return a.exec();
}
如果调用其他程序实现单例运行
//#include "mainwindow.h"
#include <QApplication>
#include <QMessageBox>
#include <windows.h>
#include <QProcess>
#include <QFileInfo>
bool CheckOne()
{
HWND hWindow=::FindWindow(NULL,L"软件名字");
HWND hWindow1=::FindWindow(NULL,L"软件名字");
if(hWindow==NULL&&hWindow1==NULL)
{
return true;
}
// 程序退出
QMessageBox::about(NULL,QObject::trUtf8("提示"),QObject::trUtf8("已有一个服务运行"));
ShowWindow(hWindow1,SW_SHOW);
return false;
}
//判断该目录下有没有该文件
bool isFileExist(QString fullFileName)
{
QFileInfo fileInfo(fullFileName);
if(fileInfo.isFile())
{
return true;
}
QMessageBox::about(NULL,QObject::trUtf8("提示"),QObject::trUtf8("要执行的exe文件名字"));
return false;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
if(!CheckOne())
{
return 0;
}
QString fullFilePath="要执行的软件的名字";
if(!isFileExist(fullFilePath))
{
return 0;
}
QProcess process;
process.startDetached(fullFilePath);
return 0;
}