How can I handle the Return key in a CEdit control?

跟風遠走 提交于 2019-12-22 03:54:41

问题


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


回答1:


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
}



回答2:


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;
}



回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/541579/how-can-i-handle-the-return-key-in-a-cedit-control

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!