The most common method is to use a mutex, similar to the following:
int WINAPI WinMain(...)
{
const char szUniqueNamedMutex[] = "com_mycompany_apps_appname";
HANDLE hHandle = CreateMutex( NULL, TRUE, szUniqueNamedMutex );
if( ERROR_ALREADY_EXISTS == GetLastError() )
{
// Program already running somewhere
return(1); // Exit program
}
// Program runs...
// Upon app closing:
ReleaseMutex( hHandle ); // Explicitly release mutex
CloseHandle( hHandle ); // close handle before terminating
return( 1 );
}
You have to make sure that you close properly - a program crash that doesn't remove the mutex could possibly prevent the program from running again, though in theory the OS will clean up any dangling mutexes once the process ends.
Another method commonly used is to search window titles for the program title:
HWND hWnd=::FindWindow(LPCTSTR lpClassName, // pointer to class name
LPCTSTR lpWindowName // pointer to window name
);
If it's null, then the window was not found, therefore the program is not running. You can use this to bring focus to the running app before closing this new instance, so the user isn't left wondering why the app didn't open.
if(hWnd != NULL)
{
ShowWindow(hWnd,SW_NORMAL);
// exit this instance
return(1);
}