C# Windows 窗体文本框 Enter 键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18059306/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:10:35  来源:igfitidea点击:

Windows Forms Textbox Enter key

c#winformstextbox

提问by Statharas.903

I have a TextBox, but I can't find any source explaining how to call a function when a button is pressed down.

我有一个文本框,但我找不到任何解释按下按钮时如何调用函数的来源。

public Simple()
{
    Text = "Server Command Line";
    Size = new Size(800, 400);

    CenterToScreen();

    Button button = new Button();
    TextBox txt = new TextBox ();

    txt.Location = new Point (20, Size.Height - 70);
    txt.Size = new Size (600, 30);
    txt.Parent = this;

    button.Text = "SEND";
    button.Size = new Size (50, 20);
    button.Location = new Point(620, Size.Height-70);
    button.Parent = this;
    button.Click += new EventHandler(Submit);
}

Some sources tell me to use a function, but I don't understand how it is going to get called.

一些消息来源告诉我使用一个函数,但我不明白它将如何被调用。

采纳答案by gzaxx

If I understood correctly you want to call a method when users press Enterwhile typing anything in textbox? If so, you have to use the KeyUpevent of TextBoxlike this:

如果我理解正确,您想在用户Enter在文本框中键入任何内容时按下时调用一个方法吗?如果是这样,你必须使用这样的KeyUp事件TextBox

public Simple()
{
    Text = "Server Command Line";
    ...

    TextBox txt = new TextBox ();
    txt.Location = new Point (20, Size.Height - 70);
    txt.Size = new Size (600, 30);
    txt.KeyUp += TextBoxKeyUp; //here we attach the event
    txt.Parent = this;    

    Button button = new Button();
    ...
}

private void TextBoxKeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        //Do something
        e.Handled = true;
    }
}

回答by Ehsan

you already have a button as well like this

你已经有一个像这样的按钮

button.Click += new EventHandler(Submit); 

if you want to call this function you can do this

如果你想调用这个函数,你可以这样做

button.PerformClick();  //this will call Submit you specified in the above statement