首先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
模态对话框可以用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();//销毁窗口,释放窗口资源
}