Sunday, February 26, 2006

Single Instance Application

Mutexes (Mutual Exclusion Locks; I believe it is also known as a spin-lock) are used to control access to shared resources. They can also be used in Windows Applications to ensure that only one instance of an application runs at any given time.

The following is an example of using a mutex in a simple Win32 application:

#undef UNICODE
#undef _UNICODE
#include

//
// SINGLE INSTANCE USING MUTEX
//

int __stdcall WinMain(HINSTANCE hPrevInstance, HINSTANCE hInstance, LPSTR CmdLine, int nCmdShow) {
HANDLE hMutex;
hMutex = CreateMutexA(NULL, FALSE, "VoilaApp");

if (GetLastError()==ERROR_ALREADY_EXISTS) {
MessageBoxA (NULL, "Error", "Already running", MB_OK);
ExitProcess(-1);
}
MessageBoxA (NULL, "Voila", "It's working", MB_OK);
return 0;
}

0 Comments:

Post a Comment

<< Home