1

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?

cbuchart
  • 10,847
  • 9
  • 53
  • 93
Bharath
  • 75
  • 8
  • Is this just for sake of not terminating the process when closing your app? Then you might just start the process detached, using `QProcess::startDetached`, or like in this answer: https://stackoverflow.com/questions/33874243/qprocessstartdetached-but-hide-console-window – king_nak Jan 26 '18 at 12:33

2 Answers2

2

Pre Qt 5 there was a project called QtSingleApplication, which allows just one instance of an application to run and would raise the running application if the user tried to open another.

If you do a Google Search for "qtsingleapplication qt5", you'll find more information about fixes for QtSingleApplication to work with Qt5.

This thread may help too.

TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85
2

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;
}
Balu
  • 2,247
  • 1
  • 18
  • 23