ere*_*eOn 23
你在寻找什么QtSingleApplication.
如果您启动应用程序的另一个实例,第一个实例甚至会得到通知(您可以传递您想要的任何数据结构).
每当启动另一个实例时,我就用它将现有应用程序带到前面.
Eti*_*ard 15
在main.cpp中使用以下代码可防止运行多个应用程序实例.我在Linux下(在QtCreator中)测试了这个代码并且它可以工作(也适用于Windows).我觉得这个解决方案简单易行.该示例适用于控制台应用程序.对于GUI应用程序,代码保持不变,请检查代码中的注释.
//main.cpp
#include <QCoreApplication> //Console application
//#include <QApplication> //GUI application
#include <QSharedMemory>
#include <QDebug>
//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();
}
Run Code Online (Sandbox Code Playgroud)
您的应用程序可以检查用户主目录中是否存在某个文件。如果存在,则应用程序退出。如果不存在,应用程序将创建它并继续。当然,如果用户一次多次启动应用程序,您可能会遇到竞争条件。但对于大多数情况,这个简单的解决方案应该足够了。
| 归档时间: |
|
| 查看次数: |
7985 次 |
| 最近记录: |