Wednesday, March 25, 2009

Make Sure Only One Instance of the Application Is Running

Place the following code in your WinMain:

// Look for the running instance of the application
char* szTitle = "My Title";
if (FindWindow(NULL, szTitle)){
SetForegroundWindow(FindWindow(NULL, szTitle));
return FALSE;
}

First, it looks for a window that has the same title as your application. If it finds it, it will make it active.
Another approach is to use a mutex:

BOOL IsFirstInstance()
{
HANDLE hMutex = CreateMutex(NULL, FALSE, "PUT A GUID HERE");
if(hMutex && GetLastError() == ERROR_ALREADY_EXISTS)
{
ReleaseMutex(hMutex);
return FALSE;
}
ReleaseMutex(hMutex);
return TRUE;
}

You call the above-mentioned function in your "InitInstance" method of your application.

No comments:

Post a Comment