17

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

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);
}

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

4

2 回答 2

37

如果我理解正确,您想在用户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;
    }
}
于 2013-08-05T13:34:12.200 回答
2

你已经有一个按钮,就像这样

button.Click += new EventHandler(Submit); 

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

button.PerformClick();  //this will call Submit you specified in the above statement
于 2013-08-05T13:34:13.610 回答