char szClassName = "Program Name";
hMutex = CreateMutex(NULL, TRUE, szClassName);
if(GetLastError() == ERROR_ALREADY_EXISTS)
hWndPrev = FindWindow(szClassName, NULL);
if(hWndPrev != NULL)
return FALSE; // this instance exits
Monday, March 24, 2008
How do I detect multiple instances of my program?
The best way to do this in Windows is to use mutex objects. Mutex objects are used to keep track of which thread currently owns a particular resource. The name comes from the fact that they are used in coordinating mutually exclusive access to shared resources. Basically, you create a mutex object upon the first instantiation of your program and then check for that object every time the program is executed. If the object is found, you know that this must be a second (or higher) instantiation. In this case, you may want to set the previous instance to be the foreground window and abort the current process.