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”的共享内存被占用时,代表已经有实例在运行了;否则的话主动去占用共享内存,打开唯一一个实例。
相关文章
- Qt之QTableView添加复选框(QAbstractItemDelegate)
- Qt-QLayout: Attempting to add QLayout “to ***“, which already has a layout的终极解决方法
- QT-Qt组件QTimer使用方法
- QT中实现程序只运行一个实例--应用程序的单例化
- Qt开发经验小技巧61-70
- Qt天气预报实例
- Qt QAtomicPointer
- Qt——正则表达式
- Qt-sqlite3数据库编程实例
- Qt开发学生信息管理系统
- Qt双缓冲机制与实例
- Qt制作一个ListView列表
- Qt GUI图形图像开发之QT表格控件QTableView详细使用方法与实例
- QT 网络编程(UDP版本)
- C++QT开发——GraphicsView(图形视图)
- Qt之QGraphicsVideoItem播放视频
- Qt easingCurve:QEasingCurve官方解析及实例
- Qt编写可视化大屏电子看板系统19-横向柱状图