Im Bild: Alte Einbände aus der Merton College library (Credit: Tom Murphy VII)

How to assign, copy or clone events in C# / NET

Problem:

When programming in C#, you may want to assign an event handler queue from one control to another like this:

    myControl.Click += anyOtherControl.Click;

This won’t work. The C# compiler tells you that events are allowed on the left side of an assignment only.

Solution:

Wrap the event queue in a delegate!

The example below creates a context menu from all Buttons it finds on a Control (like a Form). The foreach statement loops through all controls. When a button is found and it’s width equals 120 pixels the magic begins. A new ToolStripItem is created. The item gets an anonymous Click event handler which in turn – via reflection – calls the buttons protected OnClick method. Voila!

void BuildCommandMenu(Control aControl) {
	foreach (Control control in aControl.Controls) {
		if (control is Button) {
			Button button = (Button) control;
			if (button.Size.Width != 120) continue;
			ToolStripItem item = GuiCommandMenu.Items.Add(button.Text);
			item.Click += delegate {
				typeof(Button).GetMethod(
					"OnClick", BindingFlags.NonPublic | BindingFlags.Instance
				).Invoke(
					button,
					new object[] {null}
				);
			};
		}
		BuildCommandMenu(control);
	}
}
This entry was posted in Public. Bookmark the permalink.