无法在WinForms文本框中捕获Enter键

时间:2009-11-28 00:36:56

标签: c# winforms visual-studio-2008

当用户在文本框中输入数字时,我希望他们能够按Enter并模拟在表单上的其他位置按更新按钮。我已经在网上找了好几个地方,这似乎是我想要的代码,但它不起作用。当数据被放入文本框并按下Enter时,我得到的只是一个ding。我究竟做错了什么? (Visual Studio 2008)

private void tbxMod_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        btnMod.PerformClick();
    }
}

7 个答案:

答案 0 :(得分:9)

您确定没有执行按钮上的点击吗?我刚做了一个测试,它对我来说很好。这是阻止“叮”声的方法:

private void tbxMod_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        btnMod.PerformClick();
        e.SuppressKeyPress = true;
    }
}

答案 1 :(得分:5)

一些想法:

  • 表单是否有一个可能正在窃取的接受按钮(在Form上设置) ret
  • 文本框是否已启用验证且失败?试着把它关掉
  • 是否启用了密钥预览功能?

答案 2 :(得分:2)

在表格的“属性”下。类别(杂项)有以下选项:

AcceptButton,CancelButton,KeyPreview,&工具提示。

当您按 Enter 键时,将AcceptButton设置为您想要单击的按钮应该可以解决问题。

答案 3 :(得分:1)

e.Handled行之后立即将true设置为btnMod.PerformClick();

希望这有帮助。

答案 4 :(得分:1)

我必须结合托马斯的回答和马克的回答。我确实在表单上设置了AcceptButton,所以我必须完成所有这些:

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

我使用了t0mm13b的e.Handled,尽管Thomas'e.SuppressKeyPress似乎也能正常运行。我不确定可能会有什么不同。

答案 5 :(得分:0)

表单属性>将KeyPreview设置为true

答案 6 :(得分:0)

下面的简单代码工作正常(按下Enter键,而在textBoxPlatypusNumber中显示“UpdatePlatypusGrid()输入”);表单的KeyPreview设置为false:

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

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