There is often a good reason to allow only one instance of an application to run at any time. One example of this is the serial debug menu application that I present in
Windows CE: Serial Debug Menu Summary. If that application were to have more than one instance the results would be unpredictable, unless you count user confusion. The input would randomly go to instance of the application based on which instance looked for input first.
One way to prevent multiple application instances is to use a mutex. The first instance would create the mutex, and subsequent instances would get a handle to an existing instance. If the mutex already exists, GetLastError() will return a value that indicates that the mutex already exists.
Example:
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
HANDLE hMutex;
hMutex = CreateMutex(NULL, TRUE, TEXT("ADSSystemTest"));
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
RETAILMSG(1, (TEXT("Application is running already\r\n")));
CloseHandle( hMutex );
return 0;
}
// Do some application functions here.
CloseHandle( hMutex );
return 1;
}
Honestly, the calls to CloseHandle() are overkill as the handles are documented to be automatically closed when the application exists, but I don’t like to leave these things to chance.
Copyright © 2009 – Bruce Eitman
All Rights Reserved