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) .

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,893 questions
C#
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.
10,936 questions
{count} votes

Accepted answer
  1. Karen Payne MVP 35,421 Reputation points
    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,475 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 85,211 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,421 Reputation points
    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 Answers by the question author, which helps users to know the answer solved the author's problem.