将事件添加到WinForms?

soo*_*ise 4 c# events winforms

我有一个TextBoxWinForm,我想每次有人按下TextBox中的一个键时执行一些代码.我正在查看事件属性菜单,并查看KeyDown事件,但不知道如何向其中添加代码.

Ada*_*ear 14

您需要为该事件添加事件处理程序.因此,在属性菜单中,双击KeyDown事件旁边的字段,Visual Studio将为您创建一个事件处理程序.它看起来像这样:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    // enter your code here
}
Run Code Online (Sandbox Code Playgroud)

您也可以自己订阅事件,而无需使用"属性"窗口.例如,在窗体的构造函数中:

textBox1.KeyDown += HandleTextBoxKeyDownEvent;
Run Code Online (Sandbox Code Playgroud)

然后实现事件处理程序:

private void HandleTextBoxKeyDownEvent(object sender, KeyEventArgs e)
{
    // enter your code here
}
Run Code Online (Sandbox Code Playgroud)