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?
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?
First you need to enable KeyPreview
in the parent control of the TextBox, just set the property to true
.
Then you need to use the KeyDown
"of the TextBox. This event is triggered whenever a key is pressed in the control and receives as a parameter a KeyEventArgs
(usually called e
), KeyEventArgs
has a property called KeyCode
which in turn is a < a href="https://msdn.microsoft.com/en-us/library/system.windows.forms.keys(v=vs.110).aspx"> Enumeration containing multiple keys
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
//Fazer algo
}
}
In the KeyDown event of your Textbox, do the following:
if (e.KeyCode == Keys.Enter)
{
//executar alguma acao.
}
Using jQuery, regardless of browser, the code for the "Enter" is 13. So just test if the button pressed was the 13, as follows:
$(document).keypress(function(e) {
if(e.which == 13) {
alert('Você pressionou enter!');
}
});