一介绍

通过编写一个QSingleApplication类,来实现Qt程序的单例化,原文的作者是在Windows Vista +Qt4.4 下实现的,不过应用在其他平台上是没问题的。(本文是我在http://www.qtcentre.org/wiki/index.php?title=SingleApplication上看到的)

二代码

方案一:使用Qt中的QSharedMemory,QLocalServer和QLocalSocket实现(不过需要在你的.pro里加上QT += network)

别的没翻译,就是大概说了一下,直接来代码吧:

// "single_application.h"#ifndef SINGLE_APPLICATION_H
#define SINGLE_APPLICATION_H#include <QApplication>
#include <QSharedMemory>
#include <QLocalServer>class SingleApplication : public QApplication{Q_OBJECT
public:SingleApplication(int &argc, char *argv[], const QString uniqueKey);bool isRunning();bool sendMessage(const QString &message);
public slots:void receiveMessage();
signals:void messageAvailable(QString message);
private:bool _isRunning;QString _uniqueKey;QSharedMemory sharedMemory;QLocalServer *localServer;static const int timeout = 1000;
};#endif // SINGLE_APPLICATION_H
// "single_application.cpp"
#include <QLocalSocket>
#include "single_application.h"SingleApplication::SingleApplication(int &argc, char *argv[], const QString uniqueKey) : QApplication(argc, argv), _uniqueKey(uniqueKey){sharedMemory.setKey(_uniqueKey);if (sharedMemory.attach())_isRunning = true;else{_isRunning = false;// create shared memory.if (!sharedMemory.create(1)){qDebug("Unable to create single instance.");return;}// create local server and listen to incomming messages from other instances.localServer = new QLocalServer(this);connect(localServer, SIGNAL(newConnection()), this, SLOT(receiveMessage()));localServer->listen(_uniqueKey);}
}// public slots.
void SingleApplication::receiveMessage()
{QLocalSocket *localSocket = localServer->nextPendingConnection();if (!localSocket->waitForReadyRead(timeout)){qDebug(localSocket->errorString().toLatin1());return;}QByteArray byteArray = localSocket->readAll();QString message = QString::fromUtf8(byteArray.constData());emit messageAvailable(message);localSocket->disconnectFromServer();
}// public functions.
bool SingleApplication::isRunning()
{return _isRunning;
}bool SingleApplication::sendMessage(const QString &message)
{if (!_isRunning)return false;QLocalSocket localSocket(this);localSocket.connectToServer(_uniqueKey, QIODevice::WriteOnly);if (!localSocket.waitForConnected(timeout)){qDebug(localSocket.errorString().toLatin1());return false;}localSocket.write(message.toUtf8());if (!localSocket.waitForBytesWritten(timeout)){qDebug(localSocket.errorString().toLatin1());return false;}localSocket.disconnectFromServer();return true;

方案二:使用Qt中的QSharedMemory,和QTimert实现,别的也没翻译,还是直接来代码吧:

// "single_application.h"
#ifndef SINGLE_APPLICATION_H
#define SINGLE_APPLICATION_H#include <QApplication>
#include <QSharedMemory>class SingleApplication : public QApplication
{Q_OBJECT
public:SingleApplication(int &argc, char *argv[], const QString uniqueKey);bool isRunning();bool sendMessage(const QString &message);
public slots:void checkForMessage();
signals:void messageAvailable(QString message);
private:bool _isRunning;QSharedMemory sharedMemory;
};#endif // SINGLE_APPLICATION_H
// "single_application.cpp"
#include <QTimer>
#include <QByteArray>
#include "single_application.h"SingleApplication::SingleApplication(int &argc, char *argv[], const QString uniqueKey) : QApplication(argc, argv)
{sharedMemory.setKey(uniqueKey);if (sharedMemory.attach())_isRunning = true;else{_isRunning = false;// attach data to shared memory.QByteArray byteArray("0"); // default value to note that no message is available.if (!sharedMemory.create(byteArray.size())){qDebug("Unable to create single instance.");return;}sharedMemory.lock();char *to = (char*)sharedMemory.data();const char *from = byteArray.data();memcpy(to, from, qMin(sharedMemory.size(), byteArray.size()));sharedMemory.unlock();// start checking for messages of other instances.QTimer *timer = new QTimer(this);connect(timer, SIGNAL(timeout()), this, SLOT(checkForMessage()));timer->start(1000);}
}// public slots.
void SingleApplication::checkForMessage()
{sharedMemory.lock();QByteArray byteArray = QByteArray((char*)sharedMemory.constData(), sharedMemory.size());sharedMemory.unlock();if (byteArray.left(1) == "0")return;byteArray.remove(0, 1);QString message = QString::fromUtf8(byteArray.constData());emit messageAvailable(message);// remove message from shared memory.byteArray = "0";sharedMemory.lock();char *to = (char*)sharedMemory.data();const char *from = byteArray.data();memcpy(to, from, qMin(sharedMemory.size(), byteArray.size()));sharedMemory.unlock();
}// public functions.
bool SingleApplication::isRunning()
{return _isRunning;
}bool SingleApplication::sendMessage(const QString &message)
{if (!_isRunning)return false;QByteArray byteArray("1");byteArray.append(message.toUtf8());byteArray.append('/0'); // < should be as char here, not a string!sharedMemory.lock();char *to = (char*)sharedMemory.data();const char *from = byteArray.data();memcpy(to, from, qMin(sharedMemory.size(), byteArray.size()));sharedMemory.unlock();return true;
}

三使用

// "main.cpp"
#include "single_application.h"
int main(int argc, char *argv[])
{SingleApplication app(argc, argv, "some unique key string");if (app.isRunning()){app.sendMessage("message from other instance.");return 0;}MainWindow *mainWindow = new MainWindow();// connect message queue to the main window.QObject::connect(&app, SIGNAL(messageAvailable(QString)), mainWindow, SLOT(receiveMessage(QString)));// show mainwindow.mainWindow->show();return app.exec();}

亲测可用。
原文地址:https://blog.csdn.net/playstudy/article/details/7796691

Qt程序单次启动(QSingleApplication类)相关推荐

  1. MFC应用程序单文档及类向导的使用

    我想不起来第一次看见你的时候,你穿的衣服是什么颜色,是晴天还是雨天,因为我从未想到,那天之后我会这么喜欢你... ----  网易云热评 一.选择MFC应用程序 二.配置新项目 三.应用程序类型 ​ ...

  2. Qt程序启动画面QSplashScreen类

    Qt程序启动画面QSplashScreen类 当程序初始化工作比较多,程序可能启动较长时间后,窗口才会显示出来,用户没准会抱怨程序响应的慢.为了改善用户体验,最好在程序初始化这段时间显示logo,或者 ...

  3. Qt实现应用程序单实例运行--LocalServer方式

    使Qt应用程序能够单实例运行的典型实现方法是使用共享内存实现.该方法实现简单,代码简洁. 但有一个致命缺陷:共享内存(QSharedMemory)实现的单程序运行,当运行环境是UNIX时,并且程序不幸 ...

  4. QT程序启动加载流程简介

    1. QT应用程序启动加载流程简介 1.1      QWS与QPA启动客户端程序区别 1.1.1   QWS(Qt Window System)介绍 QWS(Qt Windows System)是Q ...

  5. 几行代码实现c++/qt程序进程单例(文件锁)

    qt程序进程单例(文件锁的方法) 原理 通过锁定文件,直至程序退出解锁,那么当程序第二次打开的时候检测到文件是锁定的,则退出 使用qt文件锁的方法 请在main函数里面使用,不要单独封装函数,保证锁没 ...

  6. QT编译发布程序后报错如缺少dll、“应用程序无法正常启动(0xc000007b)”的可能解决方法

    QT编译发布程序后报错如缺少dll."应用程序无法正常启动(0xc000007b)"的可能解决方法 参考文章: (1)QT编译发布程序后报错如缺少dll."应用程序无法正 ...

  7. ubuntu进入桌面自动启动脚本_在 Ubuntu 下开机自启动自己的 QT 程序而不启动 Ubuntu 的桌面...

    1. /etc/profile 方式 实现这个功能,要完成两步: 1.系统设置-> 用户账户-> 点击我的账户-> 点击右上角的解锁-> 打开自动登录-> 点击右上角的锁 ...

  8. Linux qt程序打包依赖库,Linux打包免安装的Qt程序(编写导出依赖包的脚本copylib.sh,程序启动脚本MyApp.sh)...

    本文介绍如何打包Qt程序,使其在没有安装Qt的系统可以运行. 默认前提:另外一个系统和本系统是同一个系统版本. 1,编写导出依赖包的脚本copylib.sh #!/bin/bash LibDir=$P ...

  9. anno arm移植Qt环境后,编译正常,程序无法正常启动问题的记录

    anno arm移植Qt环境后,编译正常,程序无法正常启动问题的记录 Cannot load library libqxcb.so: (libQt5XcbQpa.so.5: symbol , vers ...

最新文章

  1. ArcGIS制图之Sub Points点抽稀
  2. 关于微机开操作票的研究22437
  3. VisualSVNServer的使用
  4. SESSIONS.ser 的问题
  5. 中英文搜索引擎收录口整理
  6. expect学习笔记及实例详解
  7. 常用的Opencv函数汇总(持续更新...)
  8. 各种语言支持wasm的情况
  9. 电脑异常关机录屏/软件/程序异常停止/安卓手机/数据丢失找回方案
  10. 安装Ruby、多版本Ruby共存、Ruby安装慢问题
  11. p2v之clonezilla(1)再生龙启动u盘制作
  12. js 全屏移动漂浮框广告栏(3w)
  13. Word中,页眉-编辑页眉中,“链接到前一节页眉”呈灰色,不可点击?
  14. 计算机因特尔网络论文,[心得]英特尔
  15. 想知道如何图片转文字?这几个方法你别错过
  16. 利用“爬虫软件获取某 TOP 级平台 11.8 亿条数据!嫌疑人被判刑!
  17. 使用cocos2dx+lua改造《剑魂之刃》的经验总结
  18. 郑大计算机专业多少分,2020年,郑大各专业分数线公布,里面门道很多,给你们一一分析...
  19. 连詹姆斯·高斯林(JAVA之父)都要被气疯掉的JAVA代码注释
  20. connectex: No connection could be made because the target machine actively refused it.

热门文章

  1. NLP炼丹笔记:Switch Transformers 朴实无华 大招秒杀
  2. 网易云信再被列入Gartner最新发布的两份CPaaS市场报告
  3. 探寻用户自定义定时任务的实践方案
  4. 活动 | 5G万物智联下互联网通信技术升级之路
  5. 12C -- ORA-28040
  6. github使用心得
  7. 利用WireShark分析由Ping产生的Internet 控制报文协议(ICMP)
  8. java的finally_java的finally用法
  9. 【OS】课设记录总结+进程整理
  10. Echarts中Option属性设置