Visual Studio C#捕获在文本框中输入密钥

时间:2012-06-01 16:38:57

标签: c# visual-studio

我正在尝试捕获Windows窗体文本框中的Enter键。我从教程中得到了这段代码:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    //
    // Detect the KeyEventArg's key enumerated constant.
    //
    if (e.KeyCode == Keys.Enter)
    {
        MessageBox.Show("You pressed enter! Good job!");
    }
    else if (e.KeyCode == Keys.Escape)
    {
        MessageBox.Show("You pressed escape! What's wrong?");
    }
}

但现在我的代码抛出了编译/构建错误:

The event 'System.Windows.Forms.Control.Enter' can only appear on the left hand
side of += or -=    Line 44 Column 84

一方面我不理解错误信息。另一方面,线44是仅具有换行符的空行。

感谢任何建议。

问候。

1 个答案:

答案 0 :(得分:1)

检查Designer文件(form.Designer.cs)

您的设计师应该是:

this.textBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown);

您可能已订阅Enter事件。这实际上不是Enter键。这是为了它,它与Leave事件配对。