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












61















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?










share|improve this question





























    61















    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?










    share|improve this question



























      61












      61








      61


      16






      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?










      share|improve this question
















      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# winforms






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Sep 26 '14 at 21:28









      GEOCHET

      18.6k156692




      18.6k156692










      asked Nov 18 '08 at 15:36







      Jason Stevens































          12 Answers
          12






          active

          oldest

          votes


















          78














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





          share|improve this answer































            31














            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.






            share|improve this answer



















            • 1





              +1 Best answer I think!

              – GETah
              Mar 5 '13 at 7:42



















            31














            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






            share|improve this answer


























            • Could You add some explanation?

              – Grzegorz Piwowarek
              Jul 25 '13 at 8:49






            • 1





              I prefer this answer, it is by far the simplest.

              – chwi
              Sep 20 '13 at 8:44






            • 3





              Why not just use Accept Button?

              – Dennys Henry
              Nov 27 '16 at 15:36





















            11














            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.






            share|improve this answer



















            • 1





              Additionally, you can set e.Handled to true to avoid the beep.

              – Ruud
              Dec 28 '12 at 13:58











            • Wow, clean and easy, I like it!

              – IamBatman
              Sep 21 '17 at 14:40



















            5














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






            share|improve this answer


























            • perfect solution for me. Thanks

              – f4d0
              Nov 9 '17 at 23:32



















            3














            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.






            share|improve this answer

































              1














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



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





              share|improve this answer































                1














                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;





                share|improve this answer































                  1














                  Add this to the Form's constructor:



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





                  share|improve this answer

































                    0














                    YOu can trap it on the keyup event http://www.itjungles.com/dotnet/c-how-to-easily-detect-enter-key-in-textbox-and-execute-a-method






                    share|improve this answer































                      0














                      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.






                      share|improve this answer































                        0














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





                        share|improve this answer























                          Your Answer






                          StackExchange.ifUsing("editor", function () {
                          StackExchange.using("externalEditor", function () {
                          StackExchange.using("snippets", function () {
                          StackExchange.snippets.init();
                          });
                          });
                          }, "code-snippets");

                          StackExchange.ready(function() {
                          var channelOptions = {
                          tags: "".split(" "),
                          id: "1"
                          };
                          initTagRenderer("".split(" "), "".split(" "), channelOptions);

                          StackExchange.using("externalEditor", function() {
                          // Have to fire editor after snippets, if snippets enabled
                          if (StackExchange.settings.snippets.snippetsEnabled) {
                          StackExchange.using("snippets", function() {
                          createEditor();
                          });
                          }
                          else {
                          createEditor();
                          }
                          });

                          function createEditor() {
                          StackExchange.prepareEditor({
                          heartbeatType: 'answer',
                          autoActivateHeartbeat: false,
                          convertImagesToLinks: true,
                          noModals: true,
                          showLowRepImageUploadWarning: true,
                          reputationToPostImages: 10,
                          bindNavPrevention: true,
                          postfix: "",
                          imageUploader: {
                          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                          allowUrls: true
                          },
                          onDemand: true,
                          discardSelector: ".discard-answer"
                          ,immediatelyShowMarkdownHelp:true
                          });


                          }
                          });














                          draft saved

                          draft discarded


















                          StackExchange.ready(
                          function () {
                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f299086%2fc-sharp-how-do-i-click-a-button-by-hitting-enter-whilst-textbox-has-focus%23new-answer', 'question_page');
                          }
                          );

                          Post as a guest















                          Required, but never shown
























                          12 Answers
                          12






                          active

                          oldest

                          votes








                          12 Answers
                          12






                          active

                          oldest

                          votes









                          active

                          oldest

                          votes






                          active

                          oldest

                          votes









                          78














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





                          share|improve this answer




























                            78














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





                            share|improve this answer


























                              78












                              78








                              78







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





                              share|improve this answer













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






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 18 '08 at 15:38









                              Marc GravellMarc Gravell

                              790k19521542557




                              790k19521542557

























                                  31














                                  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.






                                  share|improve this answer



















                                  • 1





                                    +1 Best answer I think!

                                    – GETah
                                    Mar 5 '13 at 7:42
















                                  31














                                  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.






                                  share|improve this answer



















                                  • 1





                                    +1 Best answer I think!

                                    – GETah
                                    Mar 5 '13 at 7:42














                                  31












                                  31








                                  31







                                  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.






                                  share|improve this answer













                                  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.







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Nov 18 '08 at 16:00









                                  Jon NortonJon Norton

                                  2,5451720




                                  2,5451720








                                  • 1





                                    +1 Best answer I think!

                                    – GETah
                                    Mar 5 '13 at 7:42














                                  • 1





                                    +1 Best answer I think!

                                    – GETah
                                    Mar 5 '13 at 7:42








                                  1




                                  1





                                  +1 Best answer I think!

                                  – GETah
                                  Mar 5 '13 at 7:42





                                  +1 Best answer I think!

                                  – GETah
                                  Mar 5 '13 at 7:42











                                  31














                                  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






                                  share|improve this answer


























                                  • Could You add some explanation?

                                    – Grzegorz Piwowarek
                                    Jul 25 '13 at 8:49






                                  • 1





                                    I prefer this answer, it is by far the simplest.

                                    – chwi
                                    Sep 20 '13 at 8:44






                                  • 3





                                    Why not just use Accept Button?

                                    – Dennys Henry
                                    Nov 27 '16 at 15:36


















                                  31














                                  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






                                  share|improve this answer


























                                  • Could You add some explanation?

                                    – Grzegorz Piwowarek
                                    Jul 25 '13 at 8:49






                                  • 1





                                    I prefer this answer, it is by far the simplest.

                                    – chwi
                                    Sep 20 '13 at 8:44






                                  • 3





                                    Why not just use Accept Button?

                                    – Dennys Henry
                                    Nov 27 '16 at 15:36
















                                  31












                                  31








                                  31







                                  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






                                  share|improve this answer















                                  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







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Jan 20 '16 at 1:04

























                                  answered Jul 25 '13 at 8:30









                                  ruviruvi

                                  49158




                                  49158













                                  • Could You add some explanation?

                                    – Grzegorz Piwowarek
                                    Jul 25 '13 at 8:49






                                  • 1





                                    I prefer this answer, it is by far the simplest.

                                    – chwi
                                    Sep 20 '13 at 8:44






                                  • 3





                                    Why not just use Accept Button?

                                    – Dennys Henry
                                    Nov 27 '16 at 15:36





















                                  • Could You add some explanation?

                                    – Grzegorz Piwowarek
                                    Jul 25 '13 at 8:49






                                  • 1





                                    I prefer this answer, it is by far the simplest.

                                    – chwi
                                    Sep 20 '13 at 8:44






                                  • 3





                                    Why not just use Accept Button?

                                    – Dennys Henry
                                    Nov 27 '16 at 15:36



















                                  Could You add some explanation?

                                  – Grzegorz Piwowarek
                                  Jul 25 '13 at 8:49





                                  Could You add some explanation?

                                  – Grzegorz Piwowarek
                                  Jul 25 '13 at 8:49




                                  1




                                  1





                                  I prefer this answer, it is by far the simplest.

                                  – chwi
                                  Sep 20 '13 at 8:44





                                  I prefer this answer, it is by far the simplest.

                                  – chwi
                                  Sep 20 '13 at 8:44




                                  3




                                  3





                                  Why not just use Accept Button?

                                  – Dennys Henry
                                  Nov 27 '16 at 15:36







                                  Why not just use Accept Button?

                                  – Dennys Henry
                                  Nov 27 '16 at 15:36













                                  11














                                  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.






                                  share|improve this answer



















                                  • 1





                                    Additionally, you can set e.Handled to true to avoid the beep.

                                    – Ruud
                                    Dec 28 '12 at 13:58











                                  • Wow, clean and easy, I like it!

                                    – IamBatman
                                    Sep 21 '17 at 14:40
















                                  11














                                  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.






                                  share|improve this answer



















                                  • 1





                                    Additionally, you can set e.Handled to true to avoid the beep.

                                    – Ruud
                                    Dec 28 '12 at 13:58











                                  • Wow, clean and easy, I like it!

                                    – IamBatman
                                    Sep 21 '17 at 14:40














                                  11












                                  11








                                  11







                                  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.






                                  share|improve this answer













                                  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.







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Jun 5 '12 at 0:31









                                  RJ LohanRJ Lohan

                                  5,41732450




                                  5,41732450








                                  • 1





                                    Additionally, you can set e.Handled to true to avoid the beep.

                                    – Ruud
                                    Dec 28 '12 at 13:58











                                  • Wow, clean and easy, I like it!

                                    – IamBatman
                                    Sep 21 '17 at 14:40














                                  • 1





                                    Additionally, you can set e.Handled to true to avoid the beep.

                                    – Ruud
                                    Dec 28 '12 at 13:58











                                  • Wow, clean and easy, I like it!

                                    – IamBatman
                                    Sep 21 '17 at 14:40








                                  1




                                  1





                                  Additionally, you can set e.Handled to true to avoid the beep.

                                  – Ruud
                                  Dec 28 '12 at 13:58





                                  Additionally, you can set e.Handled to true to avoid the beep.

                                  – Ruud
                                  Dec 28 '12 at 13:58













                                  Wow, clean and easy, I like it!

                                  – IamBatman
                                  Sep 21 '17 at 14:40





                                  Wow, clean and easy, I like it!

                                  – IamBatman
                                  Sep 21 '17 at 14:40











                                  5














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






                                  share|improve this answer


























                                  • perfect solution for me. Thanks

                                    – f4d0
                                    Nov 9 '17 at 23:32
















                                  5














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






                                  share|improve this answer


























                                  • perfect solution for me. Thanks

                                    – f4d0
                                    Nov 9 '17 at 23:32














                                  5












                                  5








                                  5







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






                                  share|improve this answer















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







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Jan 26 '16 at 11:15









                                  Robert

                                  4,0701252107




                                  4,0701252107










                                  answered Jan 26 '16 at 10:55









                                  user5841303user5841303

                                  5111




                                  5111













                                  • perfect solution for me. Thanks

                                    – f4d0
                                    Nov 9 '17 at 23:32



















                                  • perfect solution for me. Thanks

                                    – f4d0
                                    Nov 9 '17 at 23:32

















                                  perfect solution for me. Thanks

                                  – f4d0
                                  Nov 9 '17 at 23:32





                                  perfect solution for me. Thanks

                                  – f4d0
                                  Nov 9 '17 at 23:32











                                  3














                                  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.






                                  share|improve this answer






























                                    3














                                    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.






                                    share|improve this answer




























                                      3












                                      3








                                      3







                                      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.






                                      share|improve this answer















                                      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.







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Nov 28 '18 at 3:19









                                      Jimi

                                      9,40741935




                                      9,40741935










                                      answered Feb 13 '14 at 10:27









                                      philx_xphilx_x

                                      1,0541021




                                      1,0541021























                                          1














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



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





                                          share|improve this answer




























                                            1














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



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





                                            share|improve this answer


























                                              1












                                              1








                                              1







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



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





                                              share|improve this answer













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



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






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Feb 26 '16 at 18:44









                                              jake marianojake mariano

                                              262




                                              262























                                                  1














                                                  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;





                                                  share|improve this answer




























                                                    1














                                                    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;





                                                    share|improve this answer


























                                                      1












                                                      1








                                                      1







                                                      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;





                                                      share|improve this answer













                                                      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;






                                                      share|improve this answer












                                                      share|improve this answer



                                                      share|improve this answer










                                                      answered Mar 14 '18 at 12:35









                                                      zdarovazdarova

                                                      114




                                                      114























                                                          1














                                                          Add this to the Form's constructor:



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





                                                          share|improve this answer






























                                                            1














                                                            Add this to the Form's constructor:



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





                                                            share|improve this answer




























                                                              1












                                                              1








                                                              1







                                                              Add this to the Form's constructor:



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





                                                              share|improve this answer















                                                              Add this to the Form's constructor:



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






                                                              share|improve this answer














                                                              share|improve this answer



                                                              share|improve this answer








                                                              edited Nov 27 '18 at 6:24









                                                              Jimi

                                                              9,40741935




                                                              9,40741935










                                                              answered Feb 25 '16 at 23:01









                                                              MichaelMichael

                                                              113




                                                              113























                                                                  0














                                                                  YOu can trap it on the keyup event http://www.itjungles.com/dotnet/c-how-to-easily-detect-enter-key-in-textbox-and-execute-a-method






                                                                  share|improve this answer




























                                                                    0














                                                                    YOu can trap it on the keyup event http://www.itjungles.com/dotnet/c-how-to-easily-detect-enter-key-in-textbox-and-execute-a-method






                                                                    share|improve this answer


























                                                                      0












                                                                      0








                                                                      0







                                                                      YOu can trap it on the keyup event http://www.itjungles.com/dotnet/c-how-to-easily-detect-enter-key-in-textbox-and-execute-a-method






                                                                      share|improve this answer













                                                                      YOu can trap it on the keyup event http://www.itjungles.com/dotnet/c-how-to-easily-detect-enter-key-in-textbox-and-execute-a-method







                                                                      share|improve this answer












                                                                      share|improve this answer



                                                                      share|improve this answer










                                                                      answered Jun 3 '10 at 5:25









                                                                      user344760user344760

                                                                      5913




                                                                      5913























                                                                          0














                                                                          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.






                                                                          share|improve this answer




























                                                                            0














                                                                            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.






                                                                            share|improve this answer


























                                                                              0












                                                                              0








                                                                              0







                                                                              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.






                                                                              share|improve this answer













                                                                              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.







                                                                              share|improve this answer












                                                                              share|improve this answer



                                                                              share|improve this answer










                                                                              answered Feb 27 '11 at 7:13









                                                                              r3st0r3r3st0r3

                                                                              1,35221739




                                                                              1,35221739























                                                                                  0














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





                                                                                  share|improve this answer




























                                                                                    0














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





                                                                                    share|improve this answer


























                                                                                      0












                                                                                      0








                                                                                      0







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





                                                                                      share|improve this answer













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






                                                                                      share|improve this answer












                                                                                      share|improve this answer



                                                                                      share|improve this answer










                                                                                      answered Oct 4 '18 at 14:25









                                                                                      Matt GregoryMatt Gregory

                                                                                      2,98532232




                                                                                      2,98532232






























                                                                                          draft saved

                                                                                          draft discarded




















































                                                                                          Thanks for contributing an answer to Stack Overflow!


                                                                                          • Please be sure to answer the question. Provide details and share your research!

                                                                                          But avoid



                                                                                          • Asking for help, clarification, or responding to other answers.

                                                                                          • Making statements based on opinion; back them up with references or personal experience.


                                                                                          To learn more, see our tips on writing great answers.




                                                                                          draft saved


                                                                                          draft discarded














                                                                                          StackExchange.ready(
                                                                                          function () {
                                                                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f299086%2fc-sharp-how-do-i-click-a-button-by-hitting-enter-whilst-textbox-has-focus%23new-answer', 'question_page');
                                                                                          }
                                                                                          );

                                                                                          Post as a guest















                                                                                          Required, but never shown





















































                                                                                          Required, but never shown














                                                                                          Required, but never shown












                                                                                          Required, but never shown







                                                                                          Required, but never shown

































                                                                                          Required, but never shown














                                                                                          Required, but never shown












                                                                                          Required, but never shown







                                                                                          Required, but never shown







                                                                                          Popular posts from this blog

                                                                                          Contact image not getting when fetch all contact list from iPhone by CNContact

                                                                                          count number of partitions of a set with n elements into k subsets

                                                                                          A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks