在main.cpp中使用以下代码可防止运行多个应用程序实例。我在Linux下测试了这个代码(在QtCreator中),它的工作原理(也适用于Windows)。我发现这个解决方案简单易用。该示例适用于控制台应用程序。该代码对于GUI应用程序保持不变,请检查代码中的注释。
//main.cpp
#include //Console application
//#include //GUI application
#include
#include
//Your QMainWindow derivated class goes here :
//#include "MainWindow.h"
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
app.processEvents();
//---- Check for another instance code snippet ----
//GUID : Generated once for your application
// you could get one GUID here: http://www.guidgenerator.com/online-guid-generator.aspx
QSharedMemory shared("62d60669-bb94-4a94-88bb-b964890a7e04");
if(!shared.create(512, QSharedMemory::ReadWrite))
{
// For a GUI application, replace this by :
// QMessageBox msgBox;
//msgBox.setText(QObject::tr("Can't start more than one instance of the application."));
//msgBox.setIcon(QMessageBox::Critical);
//msgBox.exec();
qWarning() << "Can't start more than one instance of the application.";
exit(0);
}
else {
qDebug() << "Application started successfully.";
}
//---- END OF Check for another instance code snippet ----
// Only one instance is running, declare MainWindow
//MainWindow myMainWindow;
//myMainWindow.show();
//We enter the Qt Event loop here, we don't leave until the MainWindow is closed
//or the console application is terminated.
return app.exec();
}