MFC Application Instance Control

An interesting question, asked days ago in one of our C++ forums, was the following:

A possible approach, based in mutex (mutual exclusion) objects, was posted a few hours later. In the proposed schema you declare a mutex object inside the MFC application class (i.e. the class header):

  1. // MFC application class declaration
  2. class CYourAppClass::CWinApp
  3. {
  4.     …
  5.     HANDLE m_Mutex_h;
  6.     UINT m_WinMsg_ui;
  7.     …
  8. }

When you define the MFC application InitInstance() method, you attempt to create the mutex -whose creation will succeed the first time, fail afterward.-

  1. BOOL CYourAppclass::InitInstance()
  2. {
  3.     m_WinMsg_ui=RegisterWindowMessage(_T(“ONNMESSAGE”));
  4.     m_Mutex_h=::CreateMutex(NULL, FALSE, STR_VIEWUTILITYMUTEX);
  5.  
  6.     if ((m_Mutex_h!=NULL)&&(GetLastError()!=ERROR_ALREADY_EXISTS))
  7.     {
  8.         // App is NOT running twice
  9.         CYourDlg dlg;
  10.         m_pMainWnd = &dlg;
  11.         INT_PTR nResponse = dlg.DoModal();
  12.     }
  13.     else
  14.     {
  15.         // App is running twice send message to running app,
  16.         // the app will now know a 2nd instance was started
  17.         ::SendMessage(HWND_BROADCAST, m_WinMsg_ui, 0, 0);
  18.     }
  19.  
  20.     // more initialization follows
  21.     …
  22. }

About the else, the solution proponent (Bordon) said the following

The “SendMessage” is only needed if you want that the running application knows a 2nd instance was started. You send a registered windows message to your running application, and your running application will receive this message and knows that a 2nd instance was started. You can create i.e. code in your message handler to bring your app to the front.

Interesting. Was marked as solution by the original guy so it seems it worked. Would you have recommended another approach?

UPDATE: Please check in the comments section an entry posted by MS MFC expert Pat Brenner about this issue.