The help you needed in C, C++, MFC
Complete tutorials with free source code
PDF Print E-mail

How to detect multiple instances of a program

There are some situations where we cannot allow 2 or more instances of the same application run at the same time. So, To achieve that, at the startup of the application, we have to check whether another instance of the application is running at that moment and exit if so. You can do this very easily. This article shows you how to do that.

What you have to do is create a mutex having a name. Once a mutex is created by a process, another mutex with same name cannot be created by that same process or any other processes running in that computer until the first mutex is deleted. So, if the creation of the mutex is failed because of it already exists, that means another instance of our application has already created the mutex, so another instance is already running.

You have to do this check at the very begriming of the program. In MFC applications, you can add this code to the InitInstance() function.

BOOL CisrunningApp::InitInstance()
{
SetLastError(ERROR_SUCCESS);
CreateMutex(NULL, TRUE, TEXT("some_unique_name"));
if(GetLastError()==ERROR_ALREADY_EXISTS) //our app is already runningExitProcess(0);

So, that's it. Notice that you cannot use a code like this.

if(CreateMutex(NULL, TRUE, TEXT("some_unique_name"))==NULL)
ExitProcess(0);

This is because if the mutex with the same name already exists, CreateMutex() do not fail so it will not return NULL.

You can download example project here.