zl程序教程

您现在的位置是:首页 >  工具

当前栏目

QT软件只允许被打开一个实例的解决方法

Qt实例方法软件 解决 一个 打开 允许
2023-09-14 09:07:02 时间

我们在编写QT应用程序时,往往期望应用软件只能被打开出一个运行实例,可以通过以下代码实现:

#include "apa.h"
#include <QApplication>
#include <QSharedMemory>
#include <QDesktopWidget>
#include <QMessageBox>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    apa w;
    w.move((QApplication::desktop()->width() - w.width())/2,\
             (QApplication::desktop()->height() - w.height())/2);
    w.show();
    QSharedMemory shared("apa");
    if(shared.attach())//共享内存被占用则直接返回
    {
        QMessageBox::information(NULL,QStringLiteral("Warning"),QStringLiteral("Application is alreadly running!"));
        return 0;
    }
    shared.create(1);//共享内存没有被占用则创建UI
    return a.exec();
}

关键在于QSharedMemory shared(“apa”),当名为“apa”的共享内存被占用时,代表已经有实例在运行了;否则的话主动去占用共享内存,打开唯一一个实例。