Search code examples
mfcmessagebox

How to prevent an application from not displaying multiple cancel messagebox's?


I am having a propertysheet and it has three pages (page1, page2, page3) respectively.For which I added as messagebox whenever Cancel button is pressed or [X] is clicked or Esc is pressed.

Steps followed:

1.Ran the application.

  1. Pressed Cancel button and message box is popped up. (Did not cancel the messagebox).

  2. Now go to the taskbar and right click on the application icon and click "close window". Exactly here the problem arose; i.e, one more message box window is popped up.

Actually this should not happen, right? It should be restricted to only one message box.

//This is being triggered when close window or cancel button is pressed.

BOOL OnQueryCancel()
{

    if(IDOK == ::MessageBox(m_hWnd, L"Closing the application",
                            L"Warning", MB_OKCANCEL | MB_ICONWARNING))
    {
        return TRUE;
    }
    return FALSE;
}

How can I prevent from not displaying multiple messagebox's? I should show focus to the already opened messagebox.


Solution

  • First, you should use AfxMessageBox, which makes it easier in MFC. Second, this is normal operation in Windows -- it's just responding to the close messages. I would add a variable to indicate the box is displayed already:

    //Part of your class
    BOOL m_bIsPromptActive;
    
    BOOL OnQueryCancel()
    {
      if( !m_bIsPromptActive)
      {
        m_bIsPromptActive = TRUE;
    
        if(IDOK == ::MessageBox(m_hWnd, L"Closing the application",
                                L"Warning", MB_OKCANCEL | MB_ICONWARNING))
        {
            return TRUE;
        }
    
        m_bIsPromptActive = FALSE;
      }
      else
      {
         // Message is already displayed. Set the focus to this window
         ::SetFocus( m_hWnd ); // or this->SetFocus();
         // You can also look at ::BringWindowToFront()
      }
    
      return FALSE;
    }