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)?
基于用户在。net文本框中输入的Enter key (key .Enter),假设关键字输入的所有权导致对文本框本身的Enter key (e)的抑制,那么什么才是执行操作的最佳方式呢?处理= 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.
考虑到这个问题的目的,假定所期望的行为不是压制窗体的默认按钮,而是要进行一些其他的自定义处理。
3 个解决方案
#1
40
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
}
}
#2
12
Inorder to link the function with the key press event of the textbox add the following code in the designer.cs of the form:
为了将函数与文本框的按键事件链接起来,在设计器中添加以下代码。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
}
}
#3
6
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
}
};
#1
40
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
}
}
#2
12
Inorder to link the function with the key press event of the textbox add the following code in the designer.cs of the form:
为了将函数与文本框的按键事件链接起来,在设计器中添加以下代码。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
}
}
#3
6
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
}
};