-
June 22nd, 2010, 09:47 AM
#1
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|