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

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

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)
{
  ::SetForegroundWindow(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

Previous article
Next article

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read