Windows窗体文本框输入密钥

Sta*_*903 14 c# textbox winforms

我有一个TextBox,但我找不到任何来源解释当按下按钮时如何调用函数.

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);
}
Run Code Online (Sandbox Code Playgroud)

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

gza*_*axx 31

如果我理解正确,当用户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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 改为执行 KeyDown 事件并添加 `e.SuppressKeyPress = true;` 可防止表单在 Enter 按下时发出噪音 (4认同)

Ehs*_*san 3

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

button.Click += new EventHandler(Submit); 
Run Code Online (Sandbox Code Playgroud)

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

button.PerformClick();  //this will call Submit you specified in the above statement
Run Code Online (Sandbox Code Playgroud)