【问题标题】:Hiding and relaunching the same instance of QApplication in Qt在 Qt 中隐藏和重新启动相同的 QApplication 实例
【发布时间】:2014-03-13 12:22:40
【问题描述】:

我有一个QApplication,其中我有一个自定义QDialog。该对话框为用户提供一组选项,然后通过QProcess 启动一个进程。虽然启动的进程仍在运行,但如果关闭,应用程序仍必须运行。为此,我根据进程是否启动重新实现了QWidgetaccept()ed 或ignore()ed 的closeEvent 事件。

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

谁能帮我解决这个问题?

【问题讨论】:

标签: c++ windows qt qapplication


【解决方案1】:

命名互斥量可以用来解决。

这个article 很有帮助。

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

【讨论】:

    【解决方案2】:

    Qt 5 之前有一个名为 QtSingleApplication 的项目,它只允许运行一个应用程序的一个实例,如果用户试图打开另一个实例,它会启动正在运行的应用程序。

    如果您在 Google 上搜索“qtsingleapplication qt5”,您会发现更多关于修复 QtSingleApplication 以与 Qt5 配合使用的信息。

    This thread 也可能有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-05
      相关资源
      最近更新 更多