Do you want to make it working or want to know how it works?
You attempt to code this shows you need both.
You don't need delegate declaration. As
Click
even is already defined in the library, appropriate delegate type is already defined. A standard recommendations for event definition say that first argument should of the the type
System.Object
, a second one — if the type
System.EventArgs
or derived. For controls, a run-time type passes as the first argument is of the same type as the control firing the event. It can be something else, like
MenuItem
(which is not derived from
System.Windows.Forms.Control
).
MyButton.Click += delegate(object sender, System.EventArgs eventArgs) {
System.Windows.Forms.MessageBox.Show(
string.Format("{0} clicked!", (Button)sender.Text));
}
Most likely, you're using C# v.3 or later, so lambda syntax is simpler, you need not specify the types of arguments as they are automatically inferred from delegate type known to the compiler from event type.
MyButton.Click += (sender, eventArgs) => {
}
These code fragment should be called anytime before your form is shown; I usually do it in the constructor of the form, at the very end, as well as all other settings and layout adjustments.
Explaining all that could take a whole article. Look for overview of delegates, events and anonymous delegates in regular help/MSDN, it should be enough. I answered to similar CodeProject Questions number of times, see, for example:
What are the advantages of delegates in C#.NET?[
^],
difference between Lambda expression and Action[
^], look at other answers and recommended reading as well.
—SA