C# How do I click a button by hitting Enter whilst textbox has focus?

C#Winforms

C# Problem Overview


I'm working with a WinForm app in C#, after I type something in a textbox I want to hit the Enter key but the textbox still has focus (flashing cursor is still in textbox), how can I achieve this?

C# Solutions


Solution 1 - C#

The simple option is just to set the forms's AcceptButton to the button you want pressed (usually "OK" etc):

    TextBox tb = new TextBox();
    Button btn = new Button { Dock = DockStyle.Bottom };
    btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); };
    Application.Run(new Form { AcceptButton = btn, Controls = { tb, btn } });

If this isn't an option, you can look at the KeyDown event etc, but that is more work...

    TextBox tb = new TextBox();
    Button btn = new Button { Dock = DockStyle.Bottom };
    btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); };
    tb.KeyDown += (sender,args) => {
        if (args.KeyCode == Keys.Return)
        {
            btn.PerformClick();
        }
    };
    Application.Run(new Form { Controls = { tb, btn } });

Solution 2 - C#

The usual way to do this is to set the Form's AcceptButton to the button you want "clicked". You can do this either in the VS designer or in code and the AcceptButton can be changed at any time.

This may or may not be applicable to your situation, but I have used this in conjunction with GotFocus events for different TextBoxes on my form to enable different behavior based on where the user hit Enter. For example:

void TextBox1_GotFocus(object sender, EventArgs e)
{
    this.AcceptButton = ProcessTextBox1;
}

void TextBox2_GotFocus(object sender, EventArgs e)
{
    this.AcceptButton = ProcessTextBox2;
}

One thing to be careful of when using this method is that you don't leave the AcceptButton set to ProcessTextBox1 when TextBox3 becomes focused. I would recommend using either the LostFocus event on the TextBoxes that set the AcceptButton, or create a GotFocus method that all of the controls that don't use a specific AcceptButton call.

Solution 3 - C#

private void textBox_KeyDown(object sender, KeyEventArgs e)
{
     if (e.KeyCode == Keys.Enter)
     {
         button.PerformClick();
         // these last two lines will stop the beep sound
         e.SuppressKeyPress = true;
         e.Handled = true;
     }
}

Bind this KeyDown event to the textbox, then when ever you press a key, this event will be fired. Inside the event we check whether user has pressed "Enter key", if so, you can perform you action

Solution 4 - C#

I came across this whilst looking for the same thing myself, and what I note is that none of the listed answers actually provide a solution when you don't want to click the 'AcceptButton' on a Form when hitting enter.

A simple use-case would be a text search box on a screen where pressing enter should 'click' the 'Search' button, not execute the Form's AcceptButton behaviour.

This little snippet will do the trick;

private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == 13)
    {
        if (!textBox.AcceptsReturn)
        {
            button1.PerformClick();
        }
    }
}

In my case, this code is part of a custom UserControl derived from TextBox, and the control has a 'ClickThisButtonOnEnter' property. But the above is a more general solution.

Solution 5 - C#

Simply set form "Accept Button" Property to button that you want to hit by Enter key. Or in load event write this.acceptbutton = btnName;

Solution 6 - C#

Most beginner friendly solution is:

  1. In your Designer, click on the text field you want this to happen. At the properties Window (default: bottom-right) click on the thunderbolt (Events). This icon is next to the alphabetical sort icon and the properties icon.

  2. Scroll down to keyDown. Click on the Dropdown field right to it. You'll notice there's nothing in there so simply press enter. Visual Studio will write you the following code:

     private void yourNameOfTextbox_KeyDown(object sender, KeyEventArgs e)
     {
    
     }
    
  3. Then simply paste this between the brackets:

     if (e.KeyCode == Keys.Enter)
     {
          yourNameOfButton.PerformClick();
     }
    

This will act as you would have clicked it.

Solution 7 - C#

In Visual Studio 2017, using c#, just add the AcceptButton attribute to your button, in my example "btnLogIn":

this.btnLogIn = new System.Windows.Forms.Button();
//....other settings
this.AcceptButton = this.btnLogIn;

Solution 8 - C#

Or you can just use this simple 2 liner code :)

if (e.KeyCode == Keys.Enter)
            button1.PerformClick();

Solution 9 - C#

Add this to the Form's constructor:

this.textboxName.KeyDown += (sender, args) => {
    if (args.KeyCode == Keys.Return)
    {
        buttonName.PerformClick();
    }
};

Solution 10 - C#

The TextBox wasn't receiving the enter key at all in my situation. The first thing I tried was changing the enter key into an input key, but I was still getting the system beep when enter was pressed. So, I subclassed and overrode the ProcessDialogKey() method and sent my own event that I could bind the click handler to.

public class EnterTextBox : TextBox
{
    [Browsable(true), EditorBrowsable]
    public event EventHandler EnterKeyPressed;

    protected override bool ProcessDialogKey(Keys keyData)
    {
        if (keyData == Keys.Enter)
        {
            EnterKeyPressed?.Invoke(this, EventArgs.Empty);
            return true;
        }
        return base.ProcessDialogKey(keyData);
    }
}

Solution 11 - C#

Solution 12 - C#

This is very much valid for WinForms. However, in WPF you need to do things differently, and it is easer. Set the IsDefault property of the Button relevant to this text-area as true.

Once you are done capturing the enter key, do not forget to toggle the properties accordingly.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJason StevensView Question on Stackoverflow
Solution 1 - C#Marc GravellView Answer on Stackoverflow
Solution 2 - C#Jon NortonView Answer on Stackoverflow
Solution 3 - C#ruviView Answer on Stackoverflow
Solution 4 - C#RJ LohanView Answer on Stackoverflow
Solution 5 - C#user5841303View Answer on Stackoverflow
Solution 6 - C#philx_xView Answer on Stackoverflow
Solution 7 - C#zdarovaView Answer on Stackoverflow
Solution 8 - C#jake marianoView Answer on Stackoverflow
Solution 9 - C#MichaelView Answer on Stackoverflow
Solution 10 - C#Matt GregoryView Answer on Stackoverflow
Solution 11 - C#user344760View Answer on Stackoverflow
Solution 12 - C#ChinmoyView Answer on Stackoverflow