When creating an application, we sometimes want to know how many buttons on the page have a delegate link for an event. The following is an example.
1. Add three buttons: 0, 1, and 2. The buttons are named button1, button2, and button3.
This. button2.click + = new system. eventhandler (this. button2_click );
This. button3.click + = new system. eventhandler (this. button3_click1 );
This. button3.click + = new system. eventhandler (this. button3_click2 );
2. You can write any code in the method:
Private void button2_click (Object sender, system. eventargs E)
{
MessageBox. Show ("button2_click ");
}
Private void button3_click1 (Object sender, system. eventargs E)
{
MessageBox. Show ("button3_click1 ");
}
Private void button3_click2 (Object sender, system. eventargs E)
{
MessageBox. Show ("button3_click2 ");
}
3. Put another Textbox (textbox1) to fill in the button name, a ListBox (listbox1) to display the button's Click Event processing method, and finally put a button, click this button to display the processing method of the Click Event of the button entered by textbox1 on listbox1. The Code is as follows:
If (this. textbox1.text = "")
MessageBox. Show ("Enter the ID of a button ");
Else
{
Button BTN = NULL;
Foreach (control C in this. Controls)
If (C. Name = This. textbox1.text)
BTN = (button) C;
This. listbox1.items. Clear ();
Propertyinfo Pi = (typeof (button). getproperty ("Events", bindingflags. instance | bindingflags. nonpublic );
Eventhandlerlist EHL = (eventhandlerlist) PI. getvalue (BTN, null );
Fieldinfo Fi = (typeof (Control). getfield ("eventclick", bindingflags. Static | bindingflags. nonpublic );
Delegate d = EHL [fi. getvalue (null)];
If (D! = NULL)
{
Foreach (Delegate De in D. getinvocationlist ())
This. listbox1.items. Add (De. method. Name );
}
Else
{
This. listbox1.items. Add ("no processing method available ");
}
}
Don't forget
Using system. reflection;
Why is it so complicated? The events of these controls are encapsulated in the eventhandlerlist, and they are not public members. Therefore, they need to be stripped out through reflection.