Brilliant article!! Here it is again, boiled down to cookbook code for your MyApp.cpp file.
Many thanks to Joseph Newcomer & Daniel Lohmann. // Mark Malyj
//Avoiding Multiple Instances of an Application
//Step 1 of 5.
//Include exclusion.h at the top of app.cpp.
#include "exclusion.h"
//Step 2 of 5.
//Define UNIQUE_GUID after the includes
//Run Visual Studio tool GUIDGEN.EXE to generate a worldwide-unique GUID for this app;
//choose option 4: registry format, Copy, and define here (DON'T USE this SAMPLE GUID!):
#define UNIQUE_GUID _T("{088FA840-B10D-11D3-BC36-006067709674}")
//Step 3 of 5.
//Use a shared variable between all instances of the application.
//This can be done by creating a shared data segment.
//Place this code block following all includes in the App .cpp file
#pragma comment(linker, "/SECTION:.shr,RWS")
#pragma data_seg(".shr")
HWND g_hWnd = NULL;
#pragma data_seg()
//Step 4 of 5.
//Place this code block at the top of App::InitInstance
bool AlreadyRunning;
HANDLE hMutexOneInstance = ::CreateMutex( NULL, TRUE,
//Choose UNIQUE_TO_DESKTOP, UNIQUE_TO_SYSTEM,
//UNIQUE_TO_SESSION, or UNIQUE_TO_TRUSTEE here:
createExclusionName(UNIQUE_GUID, UNIQUE_TO_DESKTOP));
AlreadyRunning = (GetLastError() == ERROR_ALREADY_EXISTS);
if (hMutexOneInstance != NULL)
{
::ReleaseMutex(hMutexOneInstance);
}
if ( AlreadyRunning )
{ /* kill this */
HWND hOther = g_hWnd;
if (hOther != NULL)
{ /* pop up */
:: SetForegroundWindow(hOther);
if (IsIconic(hOther))
{ /* restore */
:: ShowWindow(hOther, SW_RESTORE);
} /* restore */
} /* pop up */
return FALSE; // terminates the creation
} /* kill this */
// ... continue with InitInstance
//Step 5 of 5.
//After Creating the Main Frame, get the handle and store it on the shared variable below.
//Place this code block at the bottom of App::InitInstance, after the mainframe has been created or loaded
g_hWnd = m_pMainWnd->m_hWnd;
//Remember to add exlusion.h, exclusion.cpp to your project (see the original article)!!