.NET TextBox - Handling the Enter Key

强颜欢笑 提交于 2020-01-09 05:27:04

问题


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)?

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.


回答1:


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:


Inorder to link the function with the key press event of the textbox add the following code in the designer.cs of the form:

 this.textbox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnKeyDownHandler);

Now define the function 'OnKeyDownHandler' in the cs file of the same form:

private void OnKeyDownHandler(object sender, KeyEventArgs e)
{

    if (e.KeyCode == Keys.Enter)
    {
       //enter key has been pressed
       // add your code
    }

}



回答3:


You can drop this into the FormLoad event:

textBox1.KeyPress += (sndr, ev) => 
{
    if (ev.KeyChar.Equals((char)13))
    {
        // call your method for action on enter
        ev.Handled = true; // suppress default handling
    }
};


来源:https://stackoverflow.com/questions/3558814/net-textbox-handling-the-enter-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!