最大化qt中单个实例应用程序的已运行实例

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

本文关键字:实例 运行 应用程序 最大化 单个 qt      更新时间:2023-10-16

我制作了一个应用程序,使用qt中的共享内存只运行一个实例
我的代码如下所示

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

现在,当用户尝试运行另一个实例时,我需要向用户显示已经运行的实例(最大化窗口)。我怎样才能做到这一点?

使用QtSingleApplication有一个简单的设置:

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;
}

要接收此消息,您应该用您想要的插槽收听信号

void QtSingleApplication::messageReceived(const QString&)