Single Instance Applications in MFC

Some of the applications need to be restricted to run as a single instance. This can be achieved very easily in MFC windows applications.
When the application is started, it has to check if there is another instance running. If there is one already running, it can display a message and quit from the environment. The MFC function FindWindow is used to find out if another instance of the Windows application is already running. If such an instance is already running, the program can exit.
This check is performed inside the CWinApp derived classes in MFC. The CWinApp::InitInstance function is the ideal place for performing such initial check-ups.
The following sample code is a code extract from a Dialog based MFC application. This code checks if there is an application already running. If it is running, it displays a messagebox and quits.

BOOL TestApp::InitInstance()

  if (!AfxSocketInit())

      return FALSE;

  // Standard initialization
  // If you are not using these features and wish to reduce the size
  // of your final executable, you should remove from the following
  // the specific initialization routines you do not need.

  #ifdef _AFXDLL
   Enable3dControls(); // Call this when using MFC in a shared DLL
   Enable3dControlsStatic(); // Call this when linking to MFC statically

  // Change the registry key under which our settings are stored.
  // TODO: You should modify this string to be something appropriate
  // such as the name of your company or organization.
  SetRegistryKey(_T("Local AppWizard-Generated Applications"));

  // To create the main window, this code creates a new frame window
  // object and then sets it as the application's main window object.
  CMainFrame* pFrame = new CMainFrame;

  m_pMainWnd = pFrame;

  // create and load the frame with its resources
   // The one and only window has been initialized, so show and update it.
    MessageBox(pFrame->GetSafeHwnd(), "One Instance of TestApp is already running!","Test",MB_OK|MB_ICONINFORMATION);
  return TRUE;

The code marked in green color is the one which has to be modified inside the Initinstance function. There are some other ways to find also. But this is one of the easier ways.