Look at the
correct answer by Manas.
I only want to add an improvement.
The "traditional" form of setting up a handler for the event is pretty bad. The code generated by Microsoft Designer is also bad and based on obsolete syntax. One bad thing is Microsoft violates its own naming rules (the do not recommend underscore character). I promote different approach which pays of soon. You should not click on events in Designer at all. Creation of them does not really accelerate your work but makes the code much less supportable.
More modern and supportable approach is based on anonymous delegates. Before showing you form, set up the events. I usually do it in form's constructor, at the end of it:
MyButton.KeyDown += delegate(object sender, KeyEventArgs eventArgs) {
LogWrite(string.Format("KeyDown - {0}", e.KeyData));
}
As you can see, it looks more simple and easier to right. Very often, you don't use one or both parameters of the handler. So, from withing the method body you can call any other method with parameters convenient for you, not for the event declaration :). This code is also more supportable and all under your control.
Now, chances are you're using C# v.3 or later. Than you can further simplify the code using lambda form of the delegate:
MyButton.KeyDown += (sender, eventArgs) => {
LogWrite(string.Format("KeyDown - {0}", e.KeyData));
}
In this form, you don't even need parameter types as they are automatically inferred from the event type. It's called
type inference.
I think this style of code is also closer to what you meant in your Question.
That's it!
Good luck,
—SAP.S.: I see the contradiction in the formulation of the question caused some argument on the source of event
Button
or
Form
.
You probably mean
Button
but code sample was about the
Form
.
The technique to be used is exactly the same for
KeyDown
, as
Form
is
Conrtol
. All what matters is what events are declared in what type.