C# 如何在文本框获得焦点时按下 Enter 键来点击按钮?

73

我正在使用C#编写WinForm应用程序,在文本框中输入内容后,我想按Enter键,但文本框仍然保持焦点(闪烁的光标仍在文本框内),我该如何实现此功能?

13个回答

89

简单的方法是将表单的AcceptButton设置为您想要按下的按钮(通常是“确定”等):

    TextBox tb = new TextBox();
    Button btn = new Button { Dock = DockStyle.Bottom };
    btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); };
    Application.Run(new Form { AcceptButton = btn, Controls = { tb, btn } });

如果这不是一个选项,你可以查看KeyDown事件等,但那需要更多的工作...

    TextBox tb = new TextBox();
    Button btn = new Button { Dock = DockStyle.Bottom };
    btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); };
    tb.KeyDown += (sender,args) => {
        if (args.KeyCode == Keys.Return)
        {
            btn.PerformClick();
        }
    };
    Application.Run(new Form { Controls = { tb, btn } });

38

通常的做法是将FormAcceptButton属性设置为您想要“单击”的按钮。您可以在VS设计器中或在代码中执行此操作,并且可以随时更改AcceptButton属性。

这可能适用于您的情况,但我已经将其与表单上不同的TextBoxGotFocus事件结合使用,以根据用户按下Enter的位置启用不同的行为。例如:

void TextBox1_GotFocus(object sender, EventArgs e)
{
    this.AcceptButton = ProcessTextBox1;
}

void TextBox2_GotFocus(object sender, EventArgs e)
{
    this.AcceptButton = ProcessTextBox2;
}

使用这种方法需要注意的一点是,当TextBox3获得焦点时,不要将AcceptButton设置为ProcessTextBox1。我建议使用在设置AcceptButtonTextBox上使用LostFocus事件,或者创建一个所有控件都调用的GotFocus方法,而这些控件不使用特定的AcceptButton


36
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
     if (e.KeyCode == Keys.Enter)
     {
         button.PerformClick();
         // these last two lines will stop the beep sound
         e.SuppressKeyPress = true;
         e.Handled = true;
     }
}

将此KeyDown事件绑定到文本框,然后每当您按键时,此事件将被触发。在事件内部,我们检查用户是否按下了“Enter键”,如果是,则可以执行您的操作。


你能添加一些解释吗? - Grzegorz Piwowarek
2
我更喜欢这个答案,它远远是最简单的。 - chwi
3
为什么不直接使用“接受按钮”? - Dennis Henry

11
我在查找同样的东西时遇到了这个问题,我注意到列出的所有答案实际上都没有提供一个解决方案,当你不想在按下Enter键时点击表单上的“AcceptButton”时。
一个简单的用例是屏幕上的文本搜索框,按Enter键应该“点击”“搜索”按钮,而不是执行表单的AcceptButton行为。
这个小片段将解决问题;
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == 13)
    {
        if (!textBox.AcceptsReturn)
        {
            button1.PerformClick();
        }
    }
}
在我的情况下,这段代码是自定义UserControl的一部分,该控件派生自TextBox,并且该控件具有“ClickThisButtonOnEnter”属性。但上述是更通用的解决方案。

1
此外,您可以将 e.Handled 设置为 true 以避免蜂鸣声。 - Ruud
哇,干净简洁,我喜欢它! - IamBatman

8

只需将表单的“接受按钮”属性设置为您想要按Enter键触发的按钮。 或者在加载事件中编写this.acceptbutton = btnName;


完美的解决方案适合我。谢谢。 - f4d0

5

最适合初学者的解决方案是:

  1. In your Designer, click on the text field you want this to happen. At the properties Window (default: bottom-right) click on the thunderbolt (Events). This icon is next to the alphabetical sort icon and the properties icon.

  2. Scroll down to keyDown. Click on the Dropdown field right to it. You'll notice there's nothing in there so simply press enter. Visual Studio will write you the following code:

    private void yourNameOfTextbox_KeyDown(object sender, KeyEventArgs e)
    {
    
    }
    
  3. Then simply paste this between the brackets:

    if (e.KeyCode == Keys.Enter)
    {
         yourNameOfButton.PerformClick();
    }
    
这将起到你点击它的作用。

4
在Visual Studio 2017中,使用C#语言,在你的按钮上添加AcceptButton属性即可,例如我的示例中的"btnLogIn"按钮:
this.btnLogIn = new System.Windows.Forms.Button();
//....other settings
this.AcceptButton = this.btnLogIn;

2
或者你可以使用这个简单的两行代码 :)
if (e.KeyCode == Keys.Enter)
            button1.PerformClick();

1
将以下内容添加到表单的构造函数中:
this.textboxName.KeyDown += (sender, args) => {
    if (args.KeyCode == Keys.Return)
    {
        buttonName.PerformClick();
    }
};

1
在我的情况下,TextBox根本没有接收到回车键。我尝试的第一件事是将回车键更改为输入键,但按下回车键时仍然会发出系统蜂鸣声。因此,我对其进行了子类化并覆盖了ProcessDialogKey()方法,并发送了自己的事件,以便我可以绑定单击处理程序。
public class EnterTextBox : TextBox
{
    [Browsable(true), EditorBrowsable]
    public event EventHandler EnterKeyPressed;

    protected override bool ProcessDialogKey(Keys keyData)
    {
        if (keyData == Keys.Enter)
        {
            EnterKeyPressed?.Invoke(this, EventArgs.Empty);
            return true;
        }
        return base.ProcessDialogKey(keyData);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接