非模态对话框的创建及使用

在开始本文之前,假设我已经派生了一个对话框类CMyDlg。
对于模态对话框,使用非常简单,通常会像以下这样使用:
void Fun()
{
        ...............
        CMyDlg mydlg;
        mydlg.DoModal();
        ................
}

而对于非模态对话框,通常会像以下这样使用
void Fun()
{
        ...............
        CMyDlg*  pMydlg = new CMyDlg;
        pMydlg->Create( IDC_MY_DLG );
        pMydlg->ShowWindow( SW_SHOW );
        ................
}
因为非模态对话框是new出来的,所以要释放对象。
微软的建议是:

A modal dialog box closes automatically when the user presses the OK or Cancel buttons or when your code calls theEndDialog member function.

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.

所以我们也按照他们的建议进行操作,

void CMyDlg::OnOK()
{
	// TODO: 在此添加专用代码和/或调用基类
	DestroyWindow();

	return;
	//CDialogEx::OnOK();
}



void CMyDlg::OnCancel()
{
	// TODO: 在此添加专用代码和/或调用基类

	DestroyWindow();

	return;
	//CDialogEx::OnCancel();
}


void CMyDlg::PostNcDestroy()
{
	// TODO: 在此添加专用代码和/或调用基类
	CDialogEx::PostNcDestroy();

	delete this;
} 




注:如果你不是像以上那样临时new一个的话,比如你可能会让它成为一个类成员对象,然后在初始化的时间创建它,在类销毁时自动销毁此模态对话框的话,那么就不应该在
PostNcDestroy处delete它,也不应当DestroyWindow()它,会引发内存操作错误。因为此时它并不是new出来的。比如:在类A中有一个成员变量为CMyDlg m_mMyDlg;  然后在类构造函数中调用m_mMyDlg.Create( IDC_MY_DLG); 

作者:山丘儿
转载请标明出处,谢谢。原文地址:http://blog.csdn.net/s634772208/article/details/46404761


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值