Search code examples
c++qtshared-memorysingle-instance

maximizing the already running instance of a single instance app in qt


I have made an application to run only single instance using shared memory in qt.
My code looks like this

int main(int argc, char *argv[])
{
    QSharedMemory sharedMemory;
    sharedMemory.setKey("4da7b8a28a378e7fa9004e7a95cf257f");
    if(!sharedMemory.create(1))
    {
        return 1; // Exit already a process running
    }
    QApplication a(argc, argv);
    Encoder *encoder = Encoder::instance();
    encoder->show();
    return a.exec();
}

Now, I need to show the already running instance to the user (Maximize the window), when they try to run another instance. How can I achieve this?


Solution

  • There is an easy setup using QtSingleApplication instead :

    QtSingleApplication app("myapp",argc, argv);
    
    if (app.isRunning()) {
            QListIterator<QString> it(messagestosend);
            QString rep("Another instance is running, so I will exit.");
            bool sentok = false;
            while(it.hasNext()){
             sentok = app.sendMessage(it.next(),1000);
                 if(!sentok)
                     break;
            }
            rep += sentok ? " Message sent ok." : " Message sending failed; the other instance may be frozen.";
            return 0;
    }
    

    To receive this message you should listen with your desired slot to the signal

    void QtSingleApplication::messageReceived(const QString&)