日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

Qt程序单次启动(QSingleApplication类)

發(fā)布時(shí)間:2025/1/21 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Qt程序单次启动(QSingleApplication类) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

一介紹

通過編寫一個(gè)QSingleApplication類,來實(shí)現(xiàn)Qt程序的單例化,原文的作者是在Windows Vista +Qt4.4 下實(shí)現(xiàn)的,不過應(yīng)用在其他平臺(tái)上是沒問題的。(本文是我在http://www.qtcentre.org/wiki/index.php?title=SingleApplication上看到的)

二代碼

方案一:使用Qt中的QSharedMemory,QLocalServer和QLocalSocket實(shí)現(xiàn)(不過需要在你的.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實(shí)現(xiàn),別的也沒翻譯,還是直接來代碼吧:

// "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();}

親測(cè)可用。
原文地址:https://blog.csdn.net/playstudy/article/details/7796691

總結(jié)

以上是生活随笔為你收集整理的Qt程序单次启动(QSingleApplication类)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。