I'm trying to ensure that only one instance of my application can be run at a time. I've been trying to use the following code:
// Check to see if or app is already running and revert
// to it. Only one can run at a time. If we find another
// version of ourself, defer to it.
HWND hwnd = FindWindow( "My App", NULL );
if( hwnd )
if( IsIconic(hwnd) )
ShowWindow( hwnd, SW_RESTORE ); // If an icon, restore
SetForegroundWindow( hwnd );
return false;// Force a call to ExitInstance and shut down
// Register our class with Windows
// Declare a WNDCLASS stucture and fill it
wc.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = DefWindowProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = AfxGetInstanceHandle();
wc.hIcon = LoadIcon(IDR_MAINFRAME);
wc.hCursor = LoadCursor(IDC_ARROW);
wc.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
wc.lpszMenuName = NULL;
wc.lpszClassName = "My App";
AfxRegisterClass( &wc );
With another instance of this app already running, FindWindow never returns a window handle. The line AfxRegisterClass() returns true indicating registration was successful, but other instances still launch.
The funny thing is this code seems to work in antoher App of mine and it was basically cut and pasted into the new App.
Is there an easier way to perform this check? Perhaps through the framework itself? How can I allow only one instance of an application to run?