向WinForms添加事件? [英] Adding Events To WinForms?
问题描述
我在WinForm上有一个 TextBox
,每次有人按下该文本框内的一个键时,我想执行一些代码。我正在查看事件属性菜单,并看到 KeyDown
事件,但不知道如何向其添加代码。
I have a TextBox
on a WinForm and I want to execute some code every time someone presses a key inside of that TextBox. I'm looking at the events properties menu, and see the KeyDown
event, but don't know how to add code to it.
推荐答案
您需要为该事件添加事件处理程序。因此,在属性菜单中,双击KeyDown事件旁边的字段,Visual Studio将为您创建一个事件处理程序。它将如下所示:
You need to add an event handler for that event. So in the properties menu, double-click on the field beside the KeyDown event and Visual Studio will create an event handler for you. It'll look something like this:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
// enter your code here
}
您也可以自己订阅活动,而无需使用属性窗口。例如,在窗体的构造函数中:
You can also subscribe to events yourself without using the Properties window. For example, in the form's constructor:
textBox1.KeyDown += HandleTextBoxKeyDownEvent;
然后实现事件处理程序:
And then implement the event handler:
private void HandleTextBoxKeyDownEvent(object sender, KeyEventArgs e)
{
// enter your code here
}
这篇关于向WinForms添加事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!