C#: Detecting Keypress and handling the event

Started by
6 comments, last by Fixxer 18 years, 4 months ago
Is there a way that I can tell if a user presses enter or return while a text box is in focus?
Advertisement
You can handle the KeyPress event of the text box and check whether the KeyChar property of the event arguments is equal to ASCII character 13.

Magius
<br><br>The Textbox control should trigger the <tt>KeyDown</tt> event [delegates take an object and an KeyEventArgs]. If KeyEventArgs.KeyCode is Keys.Enter or Keys.Return [they actually look to be different names for the same thing] viola, enter key pressed.
I still dont know what it should be like, can anyone post a code snippet?
private void textBox1_KeyPress(object sender, KeyPressEventArgs e){     if(e.KeyChar == (char)13)     {          MessageBox.Show("Enter key pressed.");          e.Handled = true;     }     e.Handled = false;}


Hope that helps!

Magius
That didnt seem to work >.<
It just makes an default sound when I press enter.
You have to make sure you hook up that event handler to the KeyPress event of the text box. You can do this through the designer or in code. The code to do this would be:

textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);


Magius
Thanks =)

This topic is closed to new replies.

Advertisement