.NET TextBox - 处理 Enter 键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3558814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
.NET TextBox - Handling the Enter Key
提问by Mark Allanson
What is definitively the best way of performing an action based on the user's input of the Enter key (Keys.Enter) in a .NET TextBox, assuming ownership of the key input that leads to suppression of the Enter key to the TextBox itself (e.Handled = true)?
根据用户Keys.Enter在 .NET 中输入的 Enter 键 ( )执行操作的最佳方式是什么TextBox,假设键输入的所有权导致抑制 TextBox 本身的 Enter 键(e.Handled = true )?
Assume for the purposes of this question that the desired behavior is not to depress the default button of the form, but rather some other custom processing that should occur.
出于此问题的目的,假设所需的行为不是按下表单的默认按钮,而是应该发生的一些其他自定义处理。
回答by It Grunt
Add a keypress event and trap the enter key
添加按键事件并捕获回车键
Programmatically it looks kinda like this:
以编程方式它看起来有点像这样:
//add the handler to the textbox
this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CheckEnterKeyPress);
Then Add a handler in code...
然后在代码中添加一个处理程序...
private void CheckEnterKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
{
// Then Do your Thang
}
}
回答by R.S.K
Inorder to link the function with the key press event of the textbox add the following code in the designer.cs of the form:
为了将函数与文本框的按键事件链接起来,在表单的designer.cs 中添加以下代码:
this.textbox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnKeyDownHandler);
Now define the function 'OnKeyDownHandler' in the cs file of the same form:
现在在相同形式的 cs 文件中定义函数 'OnKeyDownHandler':
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//enter key has been pressed
// add your code
}
}
回答by Nate
You can drop this into the FormLoad event:
您可以将其放入 FormLoad 事件中:
textBox1.KeyPress += (sndr, ev) =>
{
if (ev.KeyChar.Equals((char)13))
{
// call your method for action on enter
ev.Handled = true; // suppress default handling
}
};

