您的位置:首页 > 其它

非模态对话框的创建与销毁

2012-11-08 23:42 169 查看
一、非模态对话框的创建
非模态对话框的创建代码一般如下:
CYourDlg *pDlg=new CYourDlg;
pDlg->Create(IDD_DLG_YOUR, this);
pDlg->ShowWindow(SW_SHOW);
01行---创建CYourDlg的对话框对象
02行---创建对话框窗口,并和01行创建的对话框对象关联。this指定该对话框窗口的父窗口
03行---显示窗口
那么,很显然,在释放的时候,既要保证释放CYourDlg对话框的对象,又要释放与之关联的对话框窗口。这样才不会存在内存泄露。

二、非模态对话框的销毁
非模态对话框相对于模态对话框,它的创建和销毁过程和模态对话框有一点区别,先看一下MSDN的原文:
When you implement a modeless dialog box, always override the OnCancel member function and call DestroyWindow from within it. Don’t call the base class CDialog::OnCancel, because it calls EndDialog, which will make the dialog box invisible but will not destroy it. You should also override PostNcDestroy for modeless dialog boxes in order to delete this, since modeless dialog boxes are usually allocated with new. Modal dialog boxes are usually constructed on the frame and do not need PostNcDestroy cleanup.

1.在非模态对话框中override OnOK和OnCancel,调用DestroyWindow
目的:释放对话框窗口
protected:
virtual void OnOK();
virtual void OnCancel();

void CYourDlg::OnOK()
{
this->DestroyWindow();
}

void CYourDlg::OnCancel()
{
this->DestroyWindow();
}

2.在非模态对话框中override PostNcDestroy,调用delete this
目的:通过delete this,释放CYourDlg对话框对象
protected:
virtual void PostNcDestroy();

void CYourDlg::PostNcDestroy()
{
CDialog::PostNcDestroy();
delete this;
}

销毁时的流程如下:
DestroyWindow()会发送WM_DESTROY和WM_NCDESTROY两个消息。
CWnd的消息映射表中WM_NCDESTROY消息对应的处理函数为afx_msg void OnNcDestroy()。
可以看下CWnd类的消息映射
BEGIN_MESSAGE_MAP(CWnd, CCmdTarget)
......
ON_WM_NCDESTROY()
......
END_MESSAGE_MAP()
OnNcDestroy调用了虚函数virtual void PostNcDestroy();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: