Re: Run App only once
I want my app open only once. If a user opens a second instance I would like
to AfxMessageBox the user and make the original instance 'flash', then close
the second instance.
Here's an example that will re-activate the existing instance:
Also consider what should happen if your computer has multiple users
logged in - if you want to enforce a single instance on multiple users
you need to use a "Global\" prefix to the mutex name.
If you know the caption bar text or class name of the window, you can
use FindWindow to identify the other instance, otherwise you could
adopt some interprocess communication method to store the window
handle - a shared variable would possibly be an easy way of achieving
this.
Here's an example that illustrates the 2 techniques:
#ifndef YOUKNOWTHECAPTION
#pragma comment(linker, "/SECTION:.shared,RWS")
#pragma data_seg(".shared")
HWND g_hWnd = NULL;
#pragma data_seg()
#endif
// g_hWnd is set when the main window is created.
BOOL CDlgApp::InitInstance()
{
bool bAlreadyRunning;
HANDLE hMutexOneInstance = CreateMutex( NULL, TRUE,
"UNIQUEIDGOESHERE" );
bAlreadyRunning = ( GetLastError() == ERROR_ALREADY_EXISTS );
if ( hMutexOneInstance )
{
ReleaseMutex( hMutexOneInstance );
}
if ( bAlreadyRunning )
{
HWND hOther;
#if YOUKNOWTHECAPTION
hOther = FindWindow( NULL, "YourKnownCaptionText" );
#else
hOther = g_hWnd;
#endif
if ( hOther != NULL )
{
SetForegroundWindow( hOther );
if ( IsIconic( hOther ) )
{
ShowWindow( hOther, SW_RESTORE );
}
}
return FALSE;
}
Dave