handling enter press on a form

Shaifali jain 420 Reputation points
2023-09-22T10:46:45.1433333+00:00

Hi ,

Can someone pls suggest how to detect if the user presses enter key on his keyboard so that we can capture that event . i don't have and don't want a button(or a hidden button) for that purpose (as the size of the form is too small) .

Developer technologies | Windows Forms
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

Answer accepted by question author
  1. Karen Payne MVP 35,591 Reputation points Volunteer Moderator
    2023-09-22T12:33:18.87+00:00

    Calling a method.

    private void Dummy()
    {
        MessageBox.Show("Test");
    }
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == (Keys.Enter))
        {
            Dummy();
            return true;
        }
    
        return base.ProcessCmdKey(ref msg, keyData);
    
    }
    
    0 comments No comments

4 additional answers

Sort by: Most helpful
  1. Johan Smarius 470 Reputation points MVP
    2023-09-22T10:59:10.9133333+00:00

    You can use the KeyPressed event for this as described in this article: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.onkeypress?view=windowsdesktop-7.0. You can use the "Keys.Enter" as the key to check.

    0 comments No comments

  2. KOZ6.0 6,735 Reputation points
    2023-09-22T11:30:50.2833333+00:00

    By setting the form's KeyPreview property to True, you can use the form's KeyPress event to capture whether the Enter key is pressed.

    However, when focus is on button, the click event takes precedence, so it cannot be detected.


  3. Castorix31 91,361 Reputation points
    2023-09-22T12:00:17.35+00:00

    One of the ways :

            protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
            {
                if (keyData == Keys.Enter)
                {
                    Console.Beep(5000, 10);
                }
                return base.ProcessCmdKey(ref msg, keyData);
            }
    
    0 comments No comments

  4. Karen Payne MVP 35,591 Reputation points Volunteer Moderator
    2023-09-22T12:34:05.7+00:00

    Calling a method

    private void Duumy()
    {
        MessageBox.Show("Test");
    }
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == (Keys.Enter))
        {
    
            Duumy();
            return true;
        }
    
        return base.ProcessCmdKey(ref msg, keyData);
    
    }
    
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.