How to identify a key in Textbox?

Asked

Viewed 726 times

1

I would like to create an event that would only be started when the user pressed "Enter" inside the Textbox, but how do I identify when the user pressed this key ?

  • Here in the msdn has a good example of how to do.

  • Is Windows Forms? WPF? Webforms? ASP.NET MVC?

3 answers

0

In your Textbox Keydown event, do the following :

if (e.KeyCode == Keys.Enter)
 {
   //executar alguma acao.
 }

0

Using jQuery, regardless of browser, the code for "Enter" is 13. So, just test if the button pressed was 13, as follows:

$(document).keypress(function(e) {
    if(e.which == 13) {
        alert('Você pressionou enter!');
    }
});
  • 1

    I think that the question is about Winforms...

0


First you need to activate the KeyPreview in the Textbox parent control, just set the property to true.

Then you need to use the event KeyDown of the Textbox. This event is triggered whenever a key is pressed in the control and takes as parameter a KeyEventArgs (is usually called e), the KeyEventArgs has a property called KeyCode which, in turn, is a enumeration containing several keys

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
     if(e.KeyCode == Keys.Enter)
     {
         //Fazer algo
     }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.