MFC Dialog

首先OnOK是对ID_OK的响应, OnCancel是对IDCANCEL的响应. 前者对应键盘的Enter, 后者对应Esc.

MFC:

1、Called when the user clicks the OK button (the button with an ID ofIDOK).

2、The framework calls this member function when the user clicks the Cancel button or presses the ESC key in a modal or modeless dialog box.

两个函数都是CDialog类的virtual的成员函数, 也就是MFC是希望你去重载它们. 两个函数有一个共同点,就是都会调用CDialog::EndDialog. 这个CDialog::EndDialog函数是在CDialog::OnOK();中调用的。EndDialog的作用如下,摘自MSDN:

Call this method to destroy a modal dialog box

Do not call EndDialog to destroy a modeless dialog box. Call CWindow::DestroyWindow instead

扫描二维码关注公众号,回复: 5862129 查看本文章

模态对话框可以用EndDialog来销毁, 非模态对话框要用DestroyWindow来销毁. 以下摘自MSDN:

If you implement the OK button in a modeless dialog box, you must override the OnOK method and call DestroyWindow inside it. Do not call the base-class method, because it calls EndDialog which makes the dialog box invisible but does not destroy it.

为什么强调用谁来销毁,因为这牵涉到资源释放的问题:

//调用基类的OnOK()函数,执行基类中的EndDialog(IDOK)函数,作用是关闭对话框,并把IDOK作为对话框的返回值,返回给调用对话(DoModal)的地方。

1、对于模态对话框:

void CMyDlg::OnOK()
{
CDialog::OnOK();
}

2、对于非模态对话框,你关闭对话框时,就不能只调用CDialog的OnOK, 还应该DestroyWindow,像下面这样:

void CMyDlg::OnOK()
{
CDialog::OnOK();//关闭窗口,窗口不可见,但是并没有销毁
DestroyWindow();//销毁窗口,释放窗口资源
}
-- 

OnOK 和OnCancel函数:

MFC默认建立的Dialog按Esc响应OnCancel,回车响应OnOK,都会关闭对话框。

而点击下方两个按钮功能相同,点击确定是响应OnOK, 点击取消调用OnCancel。

而OnOK和OnCancel之间是有区别的:

CDialog::OnOK首先调用UpdateData(TRUE)将数据传给对话框成员变量,然后调用CDialog::EndDialog关闭对话框。 
CDialog::OnCancel只调用CDialog::EndDialog关闭对话框。  

所以我们在销毁dialog需要进行一些数据交换就可以在OnOK中进行。


/*
* Dialog Box Command IDs
*/
#define IDOK 1
#define IDCANCEL 2

INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: 在此放置处理何时用
// “确定”来关闭对话框的代码
}
else if (nResponse == IDCANCEL)
{
// TODO: 在此放置处理何时用
// “取消”来关闭对话框的代码
}
else if (nResponse == -1)
{
TRACE(traceAppMsg, 0, "警告: 对话框创建失败,应用程序将意外终止。\n");
}

在对话框程序中,

1)用户点击X关闭按钮,调用的是CDialog::OnCancel函

猜你喜欢

转载自www.cnblogs.com/youxin/p/10696513.html
MFC