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

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?

This question is related to c# winforms

The answer is


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

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

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

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.


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.


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.


Add this to the Form's constructor:

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

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.


Add this to the Form's constructor:

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

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

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.


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


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.


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


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

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


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.



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

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.


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.


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

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;


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;

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

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

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


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