C++: Determine if Only One Instance Is Running


This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.

Microsoft Windows

Works with: Windows version 2000 or later

This line needs to be near the top of the file (or in stdafx.h, if you use one.)

#include <afx.h>

You need a variable of type HANDLE with the same lifetime as your program. Perhaps as a member of your CWinApp object.

HANDLE mutex;

At the earliest possible point in your program, you need to initialize it and perform your check. “MyApp” should be a string unique to your application. See here for full details.

mutex = CreateMutex( NULL, TRUE, "MyApp" );
if ( GetLastError() == ERROR_ALREADY_EXISTS )
	// There's another instance running.  What do you do?

Finally, near the end of your program, you need to close the mutex.

CloseHandle( mutex );


Content is available under GNU Free Documentation License 1.2.