sohel14_cse_ju
sohel14_cse_ju

Reputation: 2521

Exit MFC app from a modal dialog

I am on a modal dialog and on the close of the modal dialog i want to exit application.

ASSERT(AfxGetApp()->m_pMainWnd != NULL);
PostMessage(WM_CLOSE, 0, 0);

But getting below exception form a member method for a private member variable of the modal:

Exception thrown: read access violation.

Is there any way to close application from ModalDialog safely?

Upvotes: 0

Views: 732

Answers (3)

T.Buys
T.Buys

Reputation: 26

You ask how to post WM_CLOSE from a dialog to end your application. and if this way to close application from ModalDialog is safely.

Yes, but you must post the WM_CLOSE to the MainWnd before closing the dialog. The MainWnd have to handle the exit of the application.

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
    ON_BN_CLICKED(IDOK, &CAboutDlg::OnBnClickedOk)
END_MESSAGE_MAP()

void CAboutDlg::OnBnClickedOk()
{
    ASSERT(AfxGetApp()->m_pMainWnd != NULL);
    AfxGetApp()->m_pMainWnd->PostMessage(WM_CLOSE, 0, 0);
    CDialogEx::OnOK();
}

Upvotes: 0

Gautam Jain
Gautam Jain

Reputation: 6849

In order to show the dialog, you would have called DoModal() from your application.

You can just exit the application after the call to DoModal();

dlg.DoModal();
//write code to exit application

You can check the return value from DoModal() and exit the application accordingly.

Upvotes: 2

Flaviu_
Flaviu_

Reputation: 1371

In your CYouModal::OnDestroy() handler, call a PostMessage for main window with WM_CLOSE id. have you tried that ?

Upvotes: 0

Related Questions