Tom Tom
Tom Tom

Reputation: 1209

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?

Upvotes: 2

Views: 615

Answers (2)

Vlad Feinstein
Vlad Feinstein

Reputation: 11311

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)

Upvotes: 2

Tom Tom
Tom Tom

Reputation: 1209

I have abandoned searching a solution if the MFC Dialog itself can distingish between modeless vs modal dialog.

This workaround works for me. I have extended the constructor to tell if it is modeless or modal.

CTestDialog::CTestDialog(CWnd* pParent /*=NULL*/, BOOL bModeless /*=false*/)
: CDialogEx(CTestDialog::IDD, pParent)
, m_bModeless(bModeless)
{
}

void CTestDialog::PostNcDestroy()
{
    CDialogEx::PostNcDestroy();
    if (m_bModeless)
        delete this;
}

void CTestDialog::OnOK()
{
    if (UpdateData(TRUE))
    {
    if (m_bModeless)
        DestroyWindow();
    else
        CDialogEx::OnOK();
    }

void CTestDialog::OnCancel()
{
    if (m_bModeless)
        DestroyWindow();
    else
        CDialogEx::OnOK();
}

Upvotes: 2

Related Questions