Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
128 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...