前言
在 MFC SDI 状态栏上加了一个编辑控件, 由于消息都被主窗口吃掉了, 只能用编辑框内的右键菜单来操作(选择, 拷贝, 剪切, 粘贴), 用起来好别扭.
做了很挫的处理, 在主窗体中处理键盘消息, 同时检测CTRL键是否按下. 相当于自己判断编辑框上是否有加速键并处理加速键.
代码片段
BOOL CMainFrame::PreTranslateMessage(MSG* pMsg)
{
CString str;
// 处理在状态栏上动态嵌入命令输入编辑框
if (pMsg->message == WM_KEYDOWN) {
switch (GetFocus()->GetDlgCtrlID()) {
case IDT_CMDLINE_EDIT:
if (VK_RETURN == pMsg->wParam) {
// 命令输入
m_MyToolBar.GetDlgItem(IDT_CMDLINE_EDIT)->GetWindowText(str);
m_MyToolBar.GetDlgItem(IDT_CMDLINE_EDIT)->SetWindowText("");
if (!UtilityHelper::FindInList(m_listCmdHistory, str)) {
m_listCmdHistory.push_back(str); ///< 只加入历史命令中没有的命令
}
m_rit_listCmdHistory = m_listCmdHistory.rbegin();
((CMainDoc*)GetActiveDocument())->AddUserCmd(str);
} else if (VK_DOWN == pMsg->wParam) {
// 命令历史的翻阅(向下)
if (m_rit_listCmdHistory != m_listCmdHistory.rend()) {
m_rit_listCmdHistory--;
}
if (m_rit_listCmdHistory == m_listCmdHistory.rend()) {
m_rit_listCmdHistory = m_listCmdHistory.rbegin();
}
if (m_rit_listCmdHistory != m_listCmdHistory.rend()) {
str = *m_rit_listCmdHistory;
m_MyToolBar.GetDlgItem(IDT_CMDLINE_EDIT)->SetWindowText(str);
}
} else if (VK_UP == pMsg->wParam) {
// 命令历史的翻阅(向上)
if (m_rit_listCmdHistory != m_listCmdHistory.rend()) {
m_rit_listCmdHistory++;
}
if (m_rit_listCmdHistory == m_listCmdHistory.rend()) {
m_rit_listCmdHistory = m_listCmdHistory.rbegin();
}
if (m_rit_listCmdHistory != m_listCmdHistory.rend()) {
str = *m_rit_listCmdHistory;
m_MyToolBar.GetDlgItem(IDT_CMDLINE_EDIT)->SetWindowText(str);
}
} else if ('C' == pMsg->wParam) {
if (IsCtrlKeyDown()) {
// process Accelerator : Ctrl + C
((CEdit*)m_MyToolBar.GetDlgItem(IDT_CMDLINE_EDIT))->Copy();
}
} else if ('X' == pMsg->wParam) {
if (IsCtrlKeyDown()) {
// process Accelerator : Ctrl + X
((CEdit*)m_MyToolBar.GetDlgItem(IDT_CMDLINE_EDIT))->Cut();
}
} else if ('V' == pMsg->wParam) {
if (IsCtrlKeyDown()) {
// process Accelerator : Ctrl + V
((CEdit*)m_MyToolBar.GetDlgItem(IDT_CMDLINE_EDIT))->Paste();
}
} else if ('A' == pMsg->wParam) {
if (IsCtrlKeyDown()) {
// process Accelerator : Ctrl + A
((CEdit*)m_MyToolBar.GetDlgItem(IDT_CMDLINE_EDIT))->SetSel(0, -1);
}
}
break;
default:
break;
}
} else if (pMsg->message == WM_MY_SETFOCUS) {
m_MyToolBar.m_MyEdit.SetFocus();
}
return CFrameWnd::PreTranslateMessage(pMsg);
}
BOOL CMainFrame::IsCtrlKeyDown() {
if ((GetKeyState(VK_LCONTROL) & 0x8000) > 0) {
return TRUE;
}
if ((GetKeyState(VK_RCONTROL) & 0x8000) > 0) {
return TRUE;
}
return FALSE;
}