visual-c++mfcdialogmodal-dialog

Distinguish modeless vs modal dialog


I want use the same class CTestDialog for a modal dialog

CTestDialog dlg;
dlg.DoModal();

and for a modeless Dialog

m_pDlg = new CTestDialog;
m_pDlg->Create(CTestDialog::IDD,this);
m_pDlg->ShowWindow(SW_SHOW);

The problem I have is at PostNcDestroy() it crashes if it is constructed as modal Dialog:

void CTestDialog::PostNcDestroy() 
{   
  CDialog::PostNcDestroy();
  delete this;                 // <= need for modeless, but Crash! if constructed as modal Dialog
}

How can I determine, in a straightforward way, if the class was constructed as modeless or modal dialog?


Solution

  • Check the dialog's m_nModalResult. If it is -1 - the dialog was modeless; otherwise it will be one of IDOK, IDCANCEL, etc. codes.

    [Edited to answer the comment]

    This is different from the original question. In the OK/Cancel handler, you can test:

    if (m_nFlags & WF_MODALLOOP)