刚开始接触MFC对话框应用程序时,因为没有做处理操作,导致在对话框界面按Esc键或Enter(回车)键,导致对话框退出。在MFC中可以通过屏蔽回车和ESC来解决对话框关闭。
方法
重写PreTranslateMessage虚函数即可解决问题。
BOOL CSoftKeyboardDlg::PreTranslateMessage(MSG* pMsg)
{
if (pMsg->message == WM_SYSKEYDOWN)//Alt+?系列热键
{
CString strKeyMap;
BOOL bAlt = ::GetKeyState(VK_MENU) & 0x8000;
if (bAlt)
{
if (pMsg->wParam == VK_F4)//屏蔽Alt+F4(用来关闭当前窗口;2、如所有窗口已关闭或最小化,则为关机快捷键,使用后会弹出一关机对话框)
return true;
else if (((pMsg->wParam >= 0x30) && (pMsg->wParam <= 0x39)) || ((pMsg->wParam >= 0x41) && (pMsg->wParam <= 0x5a)))//Alt+?热键(?在0-9,A-Z)
{
strKeyMap.Format(_T("Alt+%c"), pMsg->wParam);
GetDlgItem(IDC_EDIT3)->SetWindowText(strKeyMap);
return true;
}
else
GetDlgItem(IDC_EDIT3)->SetWindowText(_T("无"));
}
else
GetDlgItem(IDC_EDIT3)->SetWindowText(_T("无"));
}
else if (pMsg->message == WM_KEYDOWN)
{
BOOL bCtrl = ::GetKeyState(VK_CONTROL) & 0x8000;
BOOL bShift = ::GetKeyState(VK_SHIFT) & 0x8000;
BOOL bAlt = ::GetKeyState(VK_MENU) & 0x8000;
BOOL bHotKey = bCtrl | bShift | bAlt;//判断是否有热键按下
CString strKeyMap;
if (pMsg->wParam == VK_RETURN) //屏蔽回车
return true;
else if (pMsg->wParam == VK_ESCAPE) //屏蔽ESC
return true;
else if (bHotKey)
{
if (((pMsg->wParam >= 0x30) && (pMsg->wParam <= 0x39)) || ((pMsg->wParam >= 0x41) && (pMsg->wParam <= 0x5a)))
{
if (bCtrl)
strKeyMap += _T("Ctrl+");
if (bShift)
strKeyMap += _T("Shift+");
if (bAlt)
strKeyMap += _T("Alt+");
strKeyMap.Format(_T("%s%c"), strKeyMap, pMsg->wParam);
GetDlgItem(IDC_EDIT3)->SetWindowText(strKeyMap);
return true;
}
else
GetDlgItem(IDC_EDIT3)->SetWindowText(_T("无"));
}
else
GetDlgItem(IDC_EDIT3)->SetWindowText(_T("无"));
}
return CDialogEx::PreTranslateMessage(pMsg);
}