Detecting Whether Another Instance of Application Already Exists


This article was contributed by
Alexey Busygin.

Environment: Windows 9x/Me/NT/2000, Visual C++ 6

Sometimes you need to detect whether another instance of your application already exists. For example popular program ICQ detects existence of another instance and shows alert message. How can you add the same functionality to your program?

MSDN shows two ways: to use FindWindow() function or to create a mutex. A third method is to use hPrevInstance parameter of the WinMain() function, but this will work only in outdated Win16-based applications.

Using the FindWindow() Function

The FindWindow() function retrieves a handle to the top-level window whose class name and window name match the specified parameters. If we have another instance of application running and this application have a window and we know at least this window’s class name or title, when we could get this window’s handle.

The convenience of this method is that if our application changes its window’s title during the execution, we could find window with knowledge only about window class name.

This method of detecting instance is convenient and in most cases it is quite enough only to use it. But when your program doesn’t have any windows or by some reason you don’t know window class name and title, using of this method will give you no result. You will have to use the second, and as I suppose, the most reliable method.

Creating a Mutex

MSDN authors offer this method. This method consists of following operations. Create a uniquely named mutex using the CreateMutex() function. CreateMutex() will succeed even if the mutex already exists, but the GetLastError() function will return ERROR_ALREADY_EXISTS. This indicates that another instance of your application exists, because it created the mutex first.

The following function implements this method.


HANDLE CreateOneAppMutex(LPCTSTR lpName)
{
HANDLE hMutex;

// Create mutex
hMutex = CreateMutex(NULL, TRUE, lpName);

switch(GetLastError())
{
case ERROR_SUCCESS:
// Mutex created successfully. There is
// no instances running

break;

case ERROR_ALREADY_EXISTS:
// Mutex already exists so there is a
// running instance of our app.

hMutex = NULL;
break;

default:
// Failed to create mutex by unknown reason
break;
}

return hMutex;
}

Demo Project

To demonstrate those methods I wrote a very simple application, which detects whether another instance already exists by creating a mutex. If another instance found, the application retrieves its window’s handle using FindWindow() function and brings another instance window to the front.

Downloads

Download demo project – 9 Kb

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read