How I show application when open application again Qt

前端 未结 2 1653
闹比i
闹比i 2021-01-19 02:06

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

2条回答
  •  悲&欢浪女
    2021-01-19 02:34

    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 
    #include 
    #include 
    #include 
    
    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.

提交回复
热议问题