Reputation: 331330
TextChanged sends a notification for every key press inside the TextBox control.
Should I be using KeyDown event?
Upvotes: 2
Views: 3222
Reputation: 273571
It depends on the rest of your Form. When you have an Accept Button, [Enter] in (almost) any control will trigger that button and it would be best to stay away from handling it separate in Textboxes.
Reversely, if you do want to handle it one or more Textboxes, don't use an Accept Button.
Upvotes: 1
Reputation: 11319
http://msdn.microsoft.com/en-us/library/system.windows.forms.keypresseventargs.keychar.aspx
Upvotes: 0
Reputation: 755259
The better event to handle here is KeyDown. KeyDown will fire when the user explicitly types into the box or another components simulates users typing by sending messages to the TextBox
. This fits the scenario you described.
If on the other hand you choose to respond to the TextChanged event, you will be responding to every occasion where the text is changed (by user or by code). This means that your event will be raised if I explicitly say
someBox.Text = Environment.NewLine;
Upvotes: 5
Reputation: 60942
The KeyPress event works for this:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
MessageBox.Show("Enter pressed!");
}
}
Upvotes: 2
Reputation: 3372
Yep, in the keydown event:
if (e.KeyCode == Keys.Enter)
{
// do stuff
}
Upvotes: 8