Can You Slyly "Steal" Event Handlers?
In a coding quandary, you seek to transfer an event handler from one control to another. Yet, the compiler stands as an unyielding barrier.
The Code Conundrum:
Button btn1 = new Button(); btn1.Click += new EventHandler(btn1_Click); Button btn2 = new Button(); // Assign btn1's event to btn2 (but met with rejection from compiler) btn2.Click += btn1.Click; // Compiler denies
Possible Theft Techniques:
The Reflection-Based Trick:
If brute force isn't your style, then donning the cloak of reflection may unveil a covert path.
using System.Reflection; // Declare event key FieldInfo eventClick = typeof(Control).GetField("EventClick", BindingFlags.NonPublic | BindingFlags.Static); // Retrieve click event PropertyInfo eventsProp = typeof(Component).GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance); EventHandlerList events1 = (EventHandlerList)eventsProp.GetValue(btn1, null); Delegate click = events1[eventClick.GetValue(null)]; // Remove from btn1, assign to btn2 events1.RemoveHandler(eventClick.GetValue(null), click); EventHandlerList events2 = (EventHandlerList)eventsProp.GetValue(btn2, null); events2.AddHandler(eventClick.GetValue(null), click);
Beware, Microsoft has erected formidable barriers to prevent such maneuvers. But for those who dare, this reflection-wielding technique grants access to hidden realms of event handling!
The above is the detailed content of How Can I Transfer an Event Handler Between Controls in C#?. For more information, please follow other related articles on the PHP Chinese website!