一、非模态对话框的创建
CYourDlg *pDlg = new CYourDlg();
pDlg->Create(IDD_DLG_YOUR, this);
pDlg->ShowWindow(SW_SHOW);
二、非模态对话框的销毁
1.在非模态对话框中重载OnOK和OnCancel,调用DestroyWindow。
protected:
virtual void OnOK();
virtual void OnCancel();
void CYourDlg::OnOK()
{
this->DestroyWindow();
}
void CYourDlg::OnCancel()
{
this->DestroyWindow();
}
2、在非模态对话框中重载PostNcDestroy,调用delete this。
protected:
virtual void PostNcDestroy();
void CYourDlg::PostNcDestroy()
{
CDialog::PostNcDestroy();
delete this;
}
以下解释为什么这么做?
在OnOK和OnCancel函数中调用了DestroyWindow函数销毁窗口,而DestroyWindow函数会发送WM_DESTROY和WM_NCDESTROY消息,也就是会执行第二步定义的PostNcDestroy函数也即销毁了窗口对应的CYourDlg对象。
看一下MSDN中的原文:
The WM_NCDESTROY message informs a window that its nonclient area is being destroyed. The DestroyWindow function sends the WM_NCDESTROY message to the window following the WM_DESTROY message. WM_DESTROY is used to free the allocated memory object associated with the window.
三、注意
如果你不是用new的方式创建非模态对话框,而是将CYourDlg的对象储存成某个类的成员变量
或存储成全局变量,就没必要在CYourDlg::PostNcDestroy()中delete this了