效果:程序启动后会单实例运行,运行时点击exe不会出现新实例。
SingleApplication.h
#ifndef SINGLEAPPLICATION_H
#define SINGLEAPPLICATION_H
#include "temp.h"
#define TIMEOUT 500
#define SOFTWARE_NAME ("any name you want to set")
class SingleApplication : public QApplication
{
Q_OBJECT
public:
SingleApplication(int &argc, char **argv);
bool IsRunning();
QWidget *g_ptrWidget;
private:
QLocalServer *m_ptrServer;
bool m_bIsRunning;
void ConnectToServer();
void CreateLocalServer();
void ActivateMainWindow();
private slots:
void slotNewPendingConnection();
};
#endif
SingleApplication.cpp
#include "SingleApplication.h"
SingleApplication::SingleApplication(int &argc, char **argv) : QApplication(argc, argv)
{
m_bIsRunning = false;
m_ptrServer = nullptr;
ConnectToServer();
}
bool SingleApplication::IsRunning()
{
return m_bIsRunning;
}
void SingleApplication::ConnectToServer()
{
QLocalSocket socket;
socket.connectToServer(SOFTWARE_NAME);
if(socket.waitForConnected(TIMEOUT))
{
qWarning()<<tr("%1已经处于运行中").arg(SOFTWARE_NAME);
m_bIsRunning = true;
}else
{
CreateLocalServer();
}
}
void SingleApplication::CreateLocalServer()
{
m_ptrServer = new QLocalServer(this);
connect(m_ptrServer, &QLocalServer::newConnection, this, &XCSingleApplication::slotNewPendingConnection);
if(!m_ptrServer->listen(SOFTWARE_NAME))
{
if(m_ptrServer->serverError() == QAbstractSocket::AddressInUseError)
{
if(QLocalServer::removeServer(SOFTWARE_NAME) == false)
{
qCritical()<<tr("清理%1残留进程失败,建议稍后或重启后再试").arg(SOFTWARE_NAME);
}else
{
m_ptrServer->listen(SOFTWARE_NAME);
return;
}
}
}
}
void SingleApplication::ActivateMainWindow()
{
if(g_ptrWidget)
{
g_ptrWidget->setWindowState(g_ptrWidget->windowState() & ~Qt::WindowMinimized);
g_ptrWidget->raise();
g_ptrWidget->activateWindow();
}
}
void SingleApplication::slotNewPendingConnection()
{
QLocalSocket *ptrSocket = m_ptrServer->nextPendingConnection();
if(ptrSocket)
{
ActivateMainWindow();
delete ptrSocket;
}
}
main.cpp
#include "SingleApplication.h"
#include "MainWidget.h"
int main(int argc, char *argv[])
{
SingleApplication a(argc, argv);
if(a.IsRunning())
{
return 0;
}
MainWidget w;
a.g_ptrWidget = &w;
return a.exec();
}
|