Run only single instance of flutter desktop application

Issue

I am working on flutter desktop app. I want to execute only single instance of app. But currently it allows me to run more than one instance. How can I allow only one .exe file of this application to run?

Solution

This is the customization in default flutter windows application properties, so we have to code in C++ for that purpose. A single window application instance can be achieved using a Mutex:

HANDLE hMutexHandle=CreateMutex(NULL, TRUE, L"my.mutex.name");
HWND handle=FindWindowA(NULL, "Test Application");

  if (GetLastError() == ERROR_ALREADY_EXISTS)
  {
     WINDOWPLACEMENT place = { sizeof(WINDOWPLACEMENT) };
         GetWindowPlacement(handle, &place);
         switch(place.showCmd)
         {
              case SW_SHOWMAXIMIZED:
                  ShowWindow(handle, SW_SHOWMAXIMIZED);
                  break;
              case SW_SHOWMINIMIZED:
                  ShowWindow(handle, SW_RESTORE);
                  break;
              default:
                  ShowWindow(handle, SW_NORMAL);
                  break;
          }
          SetWindowPos(0, HWND_TOP, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE);
          SetForegroundWindow(handle);
          return 0;
  }

Opening the win32_window.cpp file and adding this code snippet at the start in CreateAndShow() method will restrict the application to a single instance.

Answered By – Dev94

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.