As I show the application when the open application again Qt

Now I have 1 application, but I do not want to open the application twice, so I use QShareMemory to detect the application when I open it twice. And my question is: how do I show the current application on the screen when the user opens the application second?

 int main(int argc, char *argv[]) { Application a(argc, argv); /*Make sure only one instance of application can run on host system at a time*/ QSharedMemory sharedMemory; sharedMemory.setKey ("Application"); if (!sharedMemory.create(1)) { qDebug() << "123123Exit already a process running"; return 0; } /**/ return a.exec(); } 

Thanks.

+5
source share
2 answers

Just use the QSingleApplication class instead of QApplication : http://doc.qt.digia.com/solutions/4/qtsingleapplication/qtsingleapplication.html

 int main(int argc, char **argv) { QtSingleApplication app(argc, argv); if (app.isRunning()) return 0; MyMainWidget mmw; app.setActivationWindow(&mmw); mmw.show(); return app.exec(); } 

This is part of the Qt solutions: https://github.com/qtproject/qt-solutions

0
source

Here's another approach in pure Qt:

Use QLocalServer and QLocalSocket to check for an application, and then use the signal slot mechanism to notify an existing one.

 #include "widget.h" #include <QApplication> #include <QObject> #include <QLocalSocket> #include <QLocalServer> int main(int argc, char *argv[]) { QApplication a(argc, argv); const QString appKey = "applicationKey"; QLocalSocket *socket = new QLocalSocket(); socket->connectToServer(appKey); if (socket->isOpen()) { socket->close(); socket->deleteLater(); return 0; } socket->deleteLater(); Widget w; QLocalServer server; QObject::connect(&server, &QLocalServer::newConnection, [&w] () { /*Set the window on the top level.*/ w.setWindowFlags(w.windowFlags() | Qt::WindowStaysOnTopHint); w.showNormal(); w.setWindowFlags(w.windowFlags() & ~Qt::WindowStaysOnTopHint ); w.showNormal(); w.activateWindow(); }); server.listen(appKey); w.show(); return a.exec(); } 

But if you are using Qt 5.3 for Windows, there is an error for QWidget::setWindowFlags and Qt::WindowStaysOnTopHint , see https://bugreports.qt.io/browse/QTBUG-30359 .

+4
source

Source: https://habr.com/ru/post/1206701/


All Articles