Visual C++ 7.1Visual C++ 8.0Visual C++ 7.0C++/CLIWindows 2000Visual C++ 6.0Windows XPMFC中级开发Visual StudioWindowsC++.NET
防止“回车”和“Esc”关闭对话框






2.56/5 (28投票s)
2005年2月11日

82723

1
防止回车键和Esc键关闭对话框。用户将通过“文件”->“关闭”或点击“x”来关闭对话框。
引言
基于对话框的应用程序默认情况下会在用户按下回车键、Esc键、“文件”->“关闭”,或点击系统菜单中的“X”(对话框/窗口的右上角)时关闭。如果您的应用程序比较复杂,并且主窗口中没有“确定”和/或“取消”按钮,那么当用户意外按下回车键(或Esc键)导致应用程序关闭时,可能会感到惊讶。想象一下,如果您在使用MS Word时,按下“回车”键就关闭了它,特别是如果您还没有保存几个小时的工作成果,那将会多么令人沮丧。
我希望我的应用程序只在用户点击系统菜单中的“X”或选择“文件”->“关闭”(或“退出”)菜单项时才关闭。
解决方案很简单。
//Disable OnCancel
void MyDialog::OnCancel()
{
}
//Disable OnOK
void MyDialog::OnOK()
{
}
//message map event handler executed when user selects the File Ext menu
item
void MyDialog::OnFileClose()
{
EndDialog(IDOK);
}
void MyDialog::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout; //if you have an about dialog
dlgAbout.DoModal();
}
//add the following code
else if ((nID & 0xFFF0) == SC_CLOSE)
{
//if user clicked the "X"
EndDialog(IDOK); //Close the dialog with IDOK (or IDCANCEL)
//---end of code you have added
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}