Sunday, February 1, 2009

[VC++] Preventing multiple instances of your application running at same time

Suppose you do not want to have more than one instance running at a time in your program then here is how can you do that. Use the below code at the begining of your application class' Initinstance() function. Now if you try to start a second copy it will show a message box saying "Application already running" and will exit.


HANDLE hMutex = 0;
hMutex = CreateMutex( 0, TRUE, "SomeUniqueNameHere" ));
if( ERROR_ALREADY_EXISTS == GetLastError())
{
CloseHandle( hMutex );
AfxMessageBox( "Application already running" );
return FALSE;
}

Idea is very simple, create a mutex with some name and if you try to create mutex with the same name (from same or any other application) then it will fail. Only thing you need to bother is of choosing a unique name for mutex !

No comments: