开发者

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.


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

Hope this helps.


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.


form properties > set KeyPreview to true


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");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜