Friday, January 30, 2009

How do I ensure that only one instance of my program runs?

Take a look at this code. The first piece of code would be called very early in your program, typically inside InitInstance for an MFC program. The unique name here is created with a little help from GUIDGEN.EXE, which is part of the platform SDK.

if (WeAreAlone ("Unique_8487B3D3-4623-4551-8ACA-EDE405FDA836"))
{
// Proceed
}
else
DebugMessage ("Error: app already running!");


BOOL CMyApp::WeAreAlone (LPSTR szName)
{
HANDLE hMutex = CreateMutex (NULL, TRUE, szName);
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
CloseHandle(hMutex);
return FALSE;
}
return TRUE;
}

Author : Bob Moore

0 nhận xét:

Post a Comment