Forcing Only One Instance of an Application to Run at a Time in Visual C++

This document is the easist way to check for multiple instances and bring the first instance on to the focus.

#pragma comment(linker, "/SECTION:.shr,RWS")
#pragma data_seg(".shr")
HWND g_hWnd = NULL;
#pragma data_seg()

On the App::InitInstance() add the code below:

//For single instance checking
if (g_hWnd)
  if (IsIconic(g_hWnd)) ::ShowWindow(g_hWnd, SW_RESTORE);
  // terminates the creation

After Creating the Main Frame, get the handle and store it on the shared variable below.

g_hWnd = m_pMainWnd->m_hWnd;

More by Author

Must Read