开发者

Adding Events To WinForms?

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.


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
}


These answers will have visual studio generate the event and bind it behind the scenes in the Designer.cs file.

If you want to know how to bind events yourself, it looks like this.

MyTextBox.KeyDown += new KeyEventHandler(MyKeyDownFunction)

private function MyKeyDownFunction(object sender, KeyEventArgs e) {
    // your code
}

If done this way, the new KeyEventHandler() part is optional. You can also use lambdas to avoid boilerplate code.

MyTextBox.KeyDown += (s, e) => {
    // s is the sender object, e is the args
}


Doubleclick the textfield next to it.


I assume you are in Visual Studio. One way would be to double click on the empty textbox on the right of the KeyDown event: VS will generate the code for you.


You need to add a handler to the event.

Double-click the KeyPress event in the textbox's Properties window to make Visual Studio generate an event handler in the code file.
You can then put any code you want to inside the event handler function. You can check which key was pressed by writing e.KeyCode.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜