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.
It works but has one disadvantage: CWinThread::m_pMainWnd may be used by AfxGetMainWnd function.
// m_pMainWnd = &dlg; // <-- remove this line.
INT_PTR nResponse = dlg.DoModal();
AfxMessageBox(_T("After closing main dialog"));
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.
That's all and don't worry anymore about AfxGetMainWnd.
AfxGetApp()->m_pMainWnd = NULL;