在Qt中隐藏和重新启动相同的QApplication实例

Hiding and relaunching the same instance of QApplication in Qt

本文关键字:QApplication 实例 重新启动 Qt 隐藏      更新时间:2023-10-16

我有一个QApplication,我有一个自定义的QDialog。对话框为用户提供一组选项,然后通过QProcess启动一个进程。当启动的进程仍在运行时,关闭的应用程序必须仍在运行。为了实现这一点,我根据进程是否启动,重新实现了QWidgetaccept()closeEventignore()的事件。

closeEvent()函数中,我隐藏了QDialog。这样,对于用户来说,应用程序将被关闭(但它将在任务管理器中运行)。我希望用户通过再次运行程序来重新启动应用程序。此时,我需要弄清楚另一个实例是否已经在运行,并且该实例应该进入前台。

有谁能告诉我怎么才能做到这一点吗?

命名互斥可以用来解决。

这篇文章很有帮助。
WINAPI WinMain(
  HINSTANCE, HINSTANCE, LPSTR, int)
{
  try {
    // Try to open the mutex.
    HANDLE hMutex = OpenMutex(
      MUTEX_ALL_ACCESS, 0, "MyApp1.0");
    if (!hMutex)
      // Mutex doesn’t exist. This is
      // the first instance so create
      // the mutex.
      hMutex = 
        CreateMutex(0, 0, "MyApp1.0");
    else
      // The mutex exists so this is the
      // the second instance so return.
      return 0;
    Application->Initialize();
    Application->CreateForm(
      __classid(TForm1), &Form1);
    Application->Run();
    // The app is closing so release
    // the mutex.
    ReleaseMutex(hMutex);
  }
  catch (Exception &exception) {
    Application->
      ShowException(&exception);
  }
  return 0;
}

在Qt 5之前,有一个叫做QtSingleApplication的项目,它只允许一个应用程序的一个实例运行,如果用户试图打开另一个实例,将引发正在运行的应用程序。

如果你在Google上搜索"qtsingleapplication qt5",你会发现更多关于qtsingleapplication与qt5一起工作的修复的信息。