Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to capture Enter key in WinForms text box

When the user is entering a number into a text box, I would like them to be able to press Enter and simulate pressing an Update button elsewhere on the form. I have looked this up several places online, and this seems to be the code I want, but it's not working. When data has been put in the text box and Enter is pressed, all I get is a ding. What am I doing wrong? (Visual Studio 2008)

private void tbxMod_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        btnMod.PerformClick();
    }
}
like image 394
Michael Hermes Avatar asked Nov 28 '09 00:11

Michael Hermes


2 Answers

Are you sure the click on the button isn't performed ? I just did a test, it works fine for me. And here's the way to prevent the "ding" sound :

private void tbxMod_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        btnMod.PerformClick();
        e.SuppressKeyPress = true;
    }
}
like image 177
Thomas Levesque Avatar answered Sep 23 '22 17:09

Thomas Levesque


A few thoughts:

  • does the form have an accept-button (set on the Form) that might be stealing ret
  • does the textbox have validation enabled and it failing? try turning that off
  • does something have key-preview enabled?
like image 22
Marc Gravell Avatar answered Sep 20 '22 17:09

Marc Gravell