简体   繁体   中英

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();
    }
}

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;
    }
}

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?

Under "Properties" of the Form. Category (Misc) has the following options:

AcceptButton, CancelButton, KeyPreview, & ToolTip.

Setting the AcceptButton to the button you want to have clicked when you press the Enter key should do the trick.

I had to combine Thomas' answer and Marc's. I did have an AcceptButton set on the form so I had to do all of this:

    private void tbxMod_Enter(object sender, EventArgs e)
    {
        AcceptButton = null;
    }

    private void tbxMod_Leave(object sender, EventArgs e)
    {
        AcceptButton = buttonOK;
    }

    private void tbxMod_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            // Click your button here or whatever
            e.Handled = true;
        }
    }

I used t0mm13b's e.Handled , though Thomas' e.SuppressKeyPress seems to work as well. I'm not sure what the difference might be.

Set e.Handled to true immediately after the line btnMod.PerformClick(); .

Hope this helps.

The simple code below works just fine (hitting the Enter key while in textBoxPlatypusNumber displays "UpdatePlatypusGrid() entered"); the form's KeyPreview is set to false:

private void textBoxPlatypusNumber_KeyDown(object sender, KeyEventArgs e) {
    if (e.KeyCode == Keys.Enter)
    {
        UpdatePlatypusGrid(); 
    }
}

private void UpdatePlatypusGrid()
{
    MessageBox.Show("UpdatePlatypusGrid() entered");
}

表单属性>将KeyPreview设置为true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM