C#: Detecting Keypress and handling the event
Is there a way that I can tell if a user presses enter or return while a text box is in focus?
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
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.
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
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:
Magius
textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
Magius
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement