Qt 只允许打开一个程序
版权声明:本文为CSDN博主「DarwinSmile」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/ct6816678/article/details/103702416
双击文件启动程序这个很好做,只需要修改文件属性,选择默认打开程序,即可。
该问题可以继续拓展使用情况:
1,无论打开多少个文件,都需要在一个程序中运行
2,如果程序处于最小化状态,双击文件后,要前置显示,并加载图像
解决问题,需要用到的技术:
1,QtSingleApplication 库
2,进程之间的通信
3,命令行参数解析,值得注意的是,当双击文件的时候,文件路径会当做参数进行传递给程序
QtSingleApplication app(“app_name”, argc, argv);
…
QStringList argFiles;
foreach(QString arg in QCoreApplication::argments())
{
if(QFileInfo(arg).exits())
argFiles.push_back(arg);
}
if (app.isRunning())
{
foreach(QString file in argFiles)
{
app.sendMessage(file);
}
app.activeWindow();
return 0;
}
QObject::connect(&app, SIGNAL(messageReceived(const QString&), &mainwindow, SLOT(openArgsFile(const QString&)));
if(argFiles.size() != 0)
{
foreach(QString file in argFiles)
{
mainwindow.openFile(file);
}
}
void MainWindow::openArgsFile(const QString& file)
{
this->setWindowState(this->windowState() & ~Qt::WindowMinimized);
this->raise();
this->activateWindow();
this->openFile();
}