Search code examples
c++windowsqtqapplication

Hiding and relaunching the same instance of QApplication in Qt


I have a QApplication in which I have a custom QDialog. The dialog offers the users a set of options and then launches a process via QProcess. While the process launched still runs, the app if closed has to still run. To achieve this, I re-implemented the closeEvent of QWidget and accept()ed or ignore()ed the event based on whether a process is launched or not.

In the closeEvent() function, I am hiding my QDialog. With this, for the user the application is closed (it will however run in the task manager). I expect the user to relaunch the application by running the program again. At this point I need to figure out that another instance is already running and that instance to should come to the foreground.

Can anyone help me with how I can achieve this?


Solution

  • Named mutex can be used to solve.

    This article is helpfull.

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