Run only single instance of flutter desktop application

Viewed 1440

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?

3 Answers

I am getting a compilation error.

The solution is this line at the end of the if block.

ReleaseMutex(hMutexHandle);

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.

open windows/runnner/win32_cpp:

// add this function above CreateAndShow 
bool CheckOneInstance()
{

    HANDLE  m_hStartEvent = CreateEventW( NULL, FALSE, FALSE, L"Global\\yourpackage" );

    if(m_hStartEvent == NULL)
    {
        CloseHandle( m_hStartEvent );
        return false;
    }


    if (GetLastError() == ERROR_ALREADY_EXISTS) {

        CloseHandle( m_hStartEvent );
        m_hStartEvent = NULL;
        // already exist
        // send message from here to existing copy of the application
        return false;
    }
    // the only instance, start in a usual way
    return true;
}

bool Win32Window::CreateAndShow(const std::wstring& title,
                                const Point& origin,
                                const Size& size) {
  //Add the check
  if( !CheckOneInstance()){
    return false;
  }
  Destroy();
  ....

}

Related