Sign in to follow this  
Arek the Absolute

MFC: Combo boxes and OnKeyDown

Recommended Posts

For various reasons I'm trying to implement a class derived from CComboBox with various adjustments to key response, but I'm hitting some rather nasty roadblocks along the way. Simply put: OnKeyDown doesn't seem to catch any key presses except for enter. I have a class that looks something approximately like this (stripped down for relevance's sake):
(from header file)
class Box : public CComboBox {
// junk here
    DECLARE_MESSAGE_MAP();
    virtual void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
}

(from source file)
BEGIN_MESSAGE_MAP(Box, CComboBox)
ON_WM_KEYDOWN()
END_MESSAGE_MAP()

void Box::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags){
    if (nChar == VK_UP){
        // this never happens
    } else if (nChar == VK_DOWN){
        // this never happens
    } else if (nChar == VK_RETURN){
        // this happens
    } else CComboBox::OnKeyDown(nChar, nRepCnt, nFlags);
}
I'm quite certain that the VK_UP and VK_DOWN bits never occur; I've placed breakpoints there without any results, whereas a breakpoint placed after the VK_RETURN comparison will work at the appropriate time. I've found at least one way to circumvent this which involves overriding the Run function in my CWinApp derived class, but that seems like a terrible hack to me, and it really seems to me there should be some way to recieve other messages out of this. In this particular example I only make use of keys like VK_UP and VK_DOWN, but in the future I'd also like to make use of others like CTRL, ALT, and the F keys as well. Does anyone have any idea why I'm not catching other keypresses, and what the best way to recieve them is?

Share this post


Link to post
Share on other sites
I had this problem some time ago, it was quite a pain to figure out why I was not receiving all the key events. Turned out that I needed to handle the WM_GETDLGCODE message, it tells Windows what key events a control wants to receive.

Add the following to your message map:

ON_WM_GETDLGCODE()


And the function is implemented like:

UINT Box::OnGetDlgCode(void)
{
return DLGC_WANTARROWS | DLGC_WANTCHARS | DLGC_WANTALLKEYS;
}


With this, you will be able to catch most keys, but I'm not sure about CTRL, ALT and the function keys.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this