MFC: How to show a message box in ExitInstance of a dialog-based application?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1

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

Threaded View

  1. #1
    ovidiucucu's Avatar
    ovidiucucu is offline Moderator/Reviewer Power Poster
    Join Date
    Feb 2003
    Location
    Iasi - Romania
    Posts
    8,026

    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.
    Code:
    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()
    {
       AfxMessageBox(_T("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.
    Code:
    void CDemoMainDialog::OnNcDestroy()
    {
       AfxGetApp()->m_pMainWnd = NULL;
       CDialog::OnNcDestroy();
    }
    That's all and don't worry anymore about AfxGetMainWnd.

    See also
    Last edited by ovidiucucu; June 27th, 2010 at 08:50 AM.
    Ovidiu Cucu
    "When in Rome, do as Romans do."
    Visit: Microsoft Virtual Academy
    Follow: https://twitter.com/#!/ovidiucucu
    My blog: http://codexpert.ro/blog/author/ovidiu-cucu/

Posting Permissions

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


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center