通过TranslateAccelerator检测快捷方式时忽略Shift键的状态

时间:2019-07-04 19:10:08

标签: c++ winapi mfc

我被困住了:如何防止在加速器转换期间考虑虚拟Shift键?例如,如果我的加速器表包含单个 Ctrl + A 条目(例如,要选择当前焦点窗口中的所有内容),那么我希望检测到相应的命令按下 Ctrl + A 以及 Ctrl + Shift + A 被按下(但是相反,我仍然希望 Alt 键发挥作用,因此 Ctrl + Shift + A 不能翻译成我的命令。

This post没有帮助。我认为我仍在消息循环中时正在调用TranslateAccelerator函数(请参阅下面的代码,如果我输入错了,请更正我的声音。)

当我看到WM_KEYDOWN消息时,我试图通过获取当前键盘状态来使Windows胜于智能,将虚拟Shift键状态手动更改为“未按下”,进行加速器转换并还原我的手动修改。在代码中:

BOOL CHexaEditor::PreTranslateMessage(PMSG pMsg){
    // pre-processing the Message
    if (::GetFocus()==m_hWnd){ // I'm not sure if this is mandatory in MFC
        if (pMsg->message==WM_KEYDOWN){
            BYTE keyboardState[256];
            ::GetKeyboardState(keyboardState);
            const BYTE shiftState0=keyboardState[VK_SHIFT];
            keyboardState[VK_SHIFT]=0; // 0 = "not pressed"
                const BOOL result=::TranslateAccelerator(m_hWnd,hDefaultAccelerators,pMsg);
            keyboardState[VK_SHIFT]=shiftState0;
            ::SetKeyboardState(keyboardState);
            return result;
        }else
            return ::TranslateAccelerator(m_hWnd,hDefaultAccelerators,pMsg);
    }else
        return FALSE;
}

到目前为止没有成功,任何帮助都值得赞赏。谢谢:-)

1 个答案:

答案 0 :(得分:1)

因此正确答案是(由于上面的ybungalobill):

BOOL CHexaEditor::PreTranslateMessage(PMSG pMsg){
    // pre-processing the Message
    if (::GetFocus()==m_hWnd){
        if (pMsg->message==WM_KEYDOWN){
            BYTE keyboardState[256];
            ::GetKeyboardState(keyboardState);
            const BYTE shiftState0=keyboardState[VK_SHIFT];
            keyboardState[VK_SHIFT]=0;
/* --> */   ::SetKeyboardState(keyboardState); // this line was missing
                const BOOL result=::TranslateAccelerator(m_hWnd,hDefaultAccelerators,pMsg);
            keyboardState[VK_SHIFT]=shiftState0;
            ::SetKeyboardState(keyboardState);
            return result;
        }else
            return ::TranslateAccelerator(m_hWnd,hDefaultAccelerators,pMsg);
    }else
        return FALSE;
}