【问题标题】:Windows Forms Textbox Enter keyWindows 窗体文本框 Enter 键
【发布时间】:2013-08-05 13:25:59
【问题描述】:

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

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

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

【问题讨论】:

标签: c# winforms textbox


【解决方案1】:

如果我理解正确,您想在用户在文本框中输入任何内容时按Enter 时调用一个方法?如果是这样,您必须像这样使用TextBoxKeyUp 事件:

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

【讨论】:

  • 改为执行 KeyDown 事件并添加 e.SuppressKeyPress = true; 可防止表单在 Enter 按下时发出噪音
【解决方案2】:

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

button.Click += new EventHandler(Submit); 

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多