12

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

4

5 回答 5

16

您还可以过滤对话框的 PreTranslateMessage 中的键。如果你得到WM_KEYDOWNVK_RETURN打电话GetFocus。如果焦点在您的编辑控件上,请调用您在编辑控件中按下返回的处理。

请注意 if 中的子句顺序依赖于短路是有效的。

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
}
于 2009-02-12T21:08:55.263 回答
5

正确的答案是处理WM_GETDLGCODE / OnGetDlgCode消息。在那里,您可以指定您希望所有键都由您的班级处理。

UINT CMyEdit::OnGetDlgCode()
{
    return CEdit::OnGetDlgCode() | DLGC_WANTALLKEYS;
}
于 2011-05-17T09:19:16.133 回答
3

确保在控件的对话框资源中设置了编辑控件样式 ES_WANTRETURN

于 2009-02-12T14:58:07.430 回答
3

默认情况下,该Return键关闭 MFC 对话框。这是因为Returnkey 导致CDialog'OnOK()函数被调用。您可以覆盖该函数以拦截Return密钥。我从这篇文章中得到了基本的想法(见最后的方法3)。

首先,确保您已使用Class Wizard将编辑控件的成员添加到对话框中,例如:

CEdit m_editFind;

接下来,您可以将以下函数原型添加到对话框的头文件中:

protected:
    virtual void OnOK();

然后您可以将以下实现添加到对话框的cpp文件中:

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

请注意:如果您的对话框中有一个带有 ID 的OK按钮IDOK,那么它也会调用OnOK()。如果这对您造成任何问题,那么您必须将按钮重定向到另一个处理函数。如何做到这一点在我上面提到的文章的方法3中也有描述。

于 2017-03-21T19:12:00.970 回答
2

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)

于 2020-04-27T19:11:36.130 回答