C#: How to make pressing enter in a text box trigger a button, yet still allow shortcuts such as "Ctrl+A" to get through?
Can you not use AcceptButton
in for the Forms Properties Window? This sets the default behaviour for the Enter key press, but you are still able to use other shortcuts.
If you want the return to trigger an action only when the user is in the textbox, you can assign the desired button the AcceptButton control, like this.
private void textBox_Enter(object sender, EventArgs e)
{
ActiveForm.AcceptButton = Button1; // Button1 will be 'clicked' when user presses return
}
private void textBox_Leave(object sender, EventArgs e)
{
ActiveForm.AcceptButton = null; // remove "return" button behavior
}
You can Use KeyPress instead of KeyUp or KeyDown its more efficient and here's how to handle
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true;
button1.PerformClick();
}
}
hope it works