The Windows application I'm working on has to be single-instance. Currently I'm able to achieve this by creating a named mutex and checking if it already exists:
CreateMutexW(NULL, TRUE, L"MY_UNIQUE_APP_IDENTIFIER");
if (GetLastError() == ERROR_ALREADY_EXISTS) {
// error message here and exit
}
Now, I'd like to avoid the message and just switch to the existing instance and close the duplicate one.
I've thought on using SetForegroundWindow
HWND hWnd = /* somehow find the HWND of the process owning the mutex*/;
if (hWnd) {
::SetForegroundWindow(hWnd);
}
Maybe using the handle of the mutex to locate the process that initially owned it and then looking for its main window (for this last step I may use this)?
I haven't find a way to make a handle-to-process search, only listing all processes and then listing all their handles, looking for the mutex, but as it sounds it seems very inefficient.
Is there a better way to do this? Either the handle-to-process search or the switch to process given the mutex handle?