How can I handle the Return key in a CEdit control

2020-08-18 05:14发布

How can I handle the Return key (VK_RETURN) in a CEdit control? The CEdit control is parented to a CDialog.

5条回答
叛逆
2楼-- · 2020-08-18 05:46

I encounter this problem myself. After a little experiment, a simple way existed if you just want to get the do something (after some editing etc) on the return (not specific for which editor you have focus) - I would just create a invisible default button, and let that button handle the 'return' key instead of default Ok button (of course, Ok button should be set default key to false)

查看更多
Lonely孤独者°
3楼-- · 2020-08-18 05:48

By default, the Return key closes an MFC dialog. This is, because the Return key causes the CDialog's OnOK() function to be called. You can override that function in order to intercept the Return key. I got the basic idea from this article (see Method 3 at the end).

First, make sure that you have added a member for the edit control to your dialog using the Class Wizard, for example:

CEdit m_editFind;

Next, you can add the following function prototype to the header file of your dialog:

protected:
    virtual void OnOK();

Then you can add the following implementation to the cpp file of your dialog:

void CMyDialog::OnOK()
{
    if(GetFocus() == &m_editFind)
    {
        // TODO: Add your handling of the Return key here.
        TRACE0("Return key in edit control pressed\n");

        // Call `return` to leave the dialog open.
        return;
    }

    // Default behavior: Close the dialog.
    CDialog::OnOK();
}

Please note: If you have an OK button in your dialog which has the ID IDOK, then it will also call OnOK(). If this causes any problems for you, then you have to redirect the button to another handler function. How to do this is also described in Method 3 of the article that I have mentioned above.

查看更多
三岁会撩人
4楼-- · 2020-08-18 06:03

You could also filter for the key in your dialog's PreTranslateMessage. If you get WM_KEYDOWN for VK_RETURN, call GetFocus. If focus is on your edit control, call your handling for return pressed in the edit control.

Note the order of clauses in the if relies on short-circuiting to be efficient.

BOOL CMyDialog::PreTranslateMessage(MSG* pMsg)
{
    if (pMsg->message == WM_KEYDOWN &&
        pMsg->wParam == VK_RETURN &&
        GetFocus() == m_EditControl)
    {
        // handle return pressed in edit control
        return TRUE; // this doesn't need processing anymore
    }
    return FALSE; // all other cases still need default processing
}
查看更多
仙女界的扛把子
5楼-- · 2020-08-18 06:04

Make certain the Edit Control style ES_WANTRETURN is set in the dialog resource for the control

查看更多
We Are One
6楼-- · 2020-08-18 06:07

The correct answer is to handle the WM_GETDLGCODE / OnGetDlgCode message. In there you can specify that you want all keys to be handled by your class.

UINT CMyEdit::OnGetDlgCode()
{
    return CEdit::OnGetDlgCode() | DLGC_WANTALLKEYS;
}
查看更多
登录 后发表回答