Search code examples
mfcmodal-dialogmessagebox

MessageBox returning instantly after a MFC DoModal() call


The topic says it all: I'm having a problem where MessageBox returns immediately (without displaying anything) if it is being called after a CDialog::DoModal(). I've tried all kinds of MessageBox: MessageBoxA, MessageBoxW, CWnd::MessageBox (by using the dialog), AfxMessageBox. None works and they return 1 immediately. I tried saving the HWND of the dialog and using that as the first parameter. I tried passing GetDesktopWindow() as the HWND parameter. I tried stuff such as MB_YESNO|MB_ICONSTOP. Nothing worked.

I suspect I'm missing something really obvious but for the life of me, I can't figure out what and I've been looking for a solution for over 2 hours now. I tried by creating a new project using the MFC Wizard, selecting the dialog template and simply adding a call to MessageBoxA right after the DoModal() call:

CdelmeDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
MessageBoxA(0, "test", "test", 0);

The dialog displays just fine, but when I click Ok or Cancel, the message box simply does not show up.

If I place the MessageBoxA() call above the DoModal() call, it works perfectly.

Edit: is there any way to prevent this behavior?


Solution

  • From memory:

    MFC framework is designed in a way that if main window (in your case dlg) exits, message loops is over and there will be no more of anything that you can do GUI-wise.

    More info (from the Creators):

    The Microsoft Foundation Class Library will automatically terminate your thread when the window referred to by m_pMainWnd is closed.

    from:

    http://msdn.microsoft.com/en-us/library/f3ddxzww(v=vs.80).aspx