Restricting your application to one instance only
Submitted by date of submission user level
Hongbing Zhu 05/05/2001 Beginner
This sample example shows how you can restrict your application to one instance only.
HANDLE hSem = CreateSemaphore(NULL, 1, 1, m_pszExeName);
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
// close the semaphore handle
CloseHandle(hSem);
// find the provious instance main window
HWND hWndPrevious = ::GetWindow(::GetDesktopWindow(), GW_CHILD);
while (::IsWindow(hWndPrevious))
{
// if the window has our tag?
if (::GetProp(hWndPrevious, m_pszExeName))
{
if (::IsIconic(hWndPrevious))
::ShowWindow(hWndPrevious, SW_RESTORE);
::SetForegroundWindow(hWndPrevious);
::SetForegroundWindow(::GetLastActivePopup(hWndPrevious));
return FALSE;
}
// continue find next window
hWndPrevious = ::GetWindow(hWndPrevious, GW_HWNDNEXT);
}
// the previous instance is exist, but can not be found
// somthing wrong?
return FALSE;
}