CDialog中默认的Enter和Esc键的处理是调用IDOK和IDCANCEL两个按钮,而这两个按钮对应的事件处理是OnOK和OnCancel。如果你的“确认”按钮不是IDOK,则Enter键不会起作用,所以你可以修改“确认”按钮的ID值。不过修改了“确认”按钮的ID值后,要自己加上事件处理代码,因为系统不会再调用默认的OnOK了,如果不处理事件,你用鼠标按“确认”按钮也不会有反应。ESC键不能用这个办法来处理,因为ESC键还会调用系统菜单上的关闭项,从而关闭对话框。所以你应该处理PreTranslateMessage,如下面这段程序就可以屏蔽掉ESC键。 BOOL CTestDlg::PreTranslateMessage(MSG* pMsg) { // TODO: Add your specialized code here and/or call the base class if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_ESCAPE) return TRUE;
return CDialog::PreTranslateMessage(pMsg); }
同意guzh() 的PreTranslateMessage()方法,比较彻底!
其实象ESC,ALT+F4,或者右上角的×键都可以直接响应WM_CLOSE消息搞定的
重载OnCancel() 屏蔽 CDialog::OnCancel(); /* The default behaviour of pressing "ESC" is calling the CDialog::OnCancel() which will close your dialog window.So override your OnCancel function to prevent it.For more detail info,please check MSDN. */ CXXXDialog::OnCancel() { //CDialog::OnCancel() }
{
if(pMsg->wParam==VK_ESCAPE)
return true;
if(pMsg->wParam==VK_RETURN)
return true;
return CDialog::PreTranslateMessage(pMsg);
}
BOOL CTestDlg::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
if (pMsg->message == WM_KEYDOWN &&
pMsg->wParam == VK_ESCAPE)
return TRUE;
return CDialog::PreTranslateMessage(pMsg);
}
/*
The default behaviour of pressing "ESC" is calling the CDialog::OnCancel()
which will close your dialog window.So override your OnCancel function to prevent
it.For more detail info,please check MSDN.
*/
CXXXDialog::OnCancel()
{
//CDialog::OnCancel()
}
重载OnOK() 屏蔽 CDialog::OnOK();就可以防止按回车退出了,