CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums
Results 1 to 1 of 1
  1. #1
    Join Date
    Feb 2003
    Iasi - Romania

    MFC: How to show a message box in ExitInstance of a dialog-based application?

    Q: If I call AfxMessageBox in ExitInstance, no message box is shown. The same thing happens in InitInstance after main dialog DoModal.
    How do I solve this?

    A: When the main window of aplication is destroyed, the MFC framework posts WM_QUIT message to the main thread. Any window created after this is destroyed immediately so no message box is shown neither in ExitInstance nor after main dialog DoModal.

    One solution found over the Internet is to remove the assignmet of main dialog address to CWinThread::m_pMainWnd.
    BOOL CDemoApp::InitInstance()
       // ...
       CDemoMainDialog dlg;
       // m_pMainWnd = &dlg; // <-- remove this line.
       INT_PTR nResponse = dlg.DoModal();
       AfxMessageBox(_T("After closing main dialog"));
       return FALSE;
    int CDemoApp::ExitInstance()
       return CWinApp::ExitInstance();
    It works but has one disadvantage: CWinThread::m_pMainWnd may be used by AfxGetMainWnd function.

    A little bit better approach: in the main dialog class, handle WM_NCDESTROY message and, before calling the base class message handler, assign NULL to m_pMainWnd.
    void CDemoMainDialog::OnNcDestroy()
       AfxGetApp()->m_pMainWnd = NULL;
    That's all and don't worry anymore about AfxGetMainWnd.

    See also
    Last edited by ovidiucucu; June 27th, 2010 at 08:50 AM.
    "When in Rome, do as Romans do."
    My latest articles:

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Click Here to Expand Forum to Full Width