Windows窗体文本框输入密钥

时间:2013-08-05 13:25:59

标签: c# winforms textbox

我有一个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);
}

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

2 个答案:

答案 0 :(得分:29)

如果我理解正确,当用户在文本框中输入任何内容时按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;
    }
}

答案 1 :(得分:2)

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

button.Click += new EventHandler(Submit); 

如果您想调用此功能,可以执行此操作

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