There are times when you want to find out when the user presses the enter key inside a specific text box, then perform some action.
If the text box is not multiline Windows sounds its annoying beep to tell the user they did something wrong.
And, if the text box is multiline, Windows does what you would expect and appends a carriage return/line feed to the end of the text in the text box.
But, what if you don’t want the carriage return/line feed characters and you also don’t want that annoying beep.
Here’s the solution:
1. Handle the KeyPress event for the text box.
2. Check the KeyChar for the Enter key.
3. Perform the code you want.
4. Set e.Handled to true before returning.
Here’s the code snippet:
private void textboxName_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13) // 13 is Enter key.
{
// CODE YOU WANT TO EXECUTE GOES HERE.
e.Handled=true; // NOTE: If you want the CRLF to be included in a multiline textbox, then leave e.Handled = false
}
}
The above code is simple, removes the annoying Windows beep and allows you to accept a user’s Enter key without appending a carriage return/line feed to the end of the text box’s text.
If you want to handle the Enter key, but also have the carriage return/line feed characters included in the text box’s text, then you just need to set the text box to multiline and leave e.Handled = false.
This works with VB.NET, C and C++ as well.