Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I show application when open application again Qt

Tags:

c++

qt

Now, I have 1 application, but I don't want to open application twice, so I using QShareMemory to detect application when open twice. And my question is: how I show current application in screen when user open application the 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.

like image 350
Hien Ngo Avatar asked Nov 12 '14 08:11

Hien Ngo


1 Answers

Here's another approach in pure Qt way:

Use QLocalServer and QLocalSocket to check the existence of application and then use signal-slot mechanism to notify the 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're using Qt 5.3 on Windows, there's a bug for QWidget::setWindowFlags and Qt::WindowStaysOnTopHint, see https://bugreports.qt.io/browse/QTBUG-30359.

like image 197
Serge45 Avatar answered Oct 25 '22 07:10

Serge45