Home > Backend Development > C++ > How Can I Transfer an Event Handler Between Controls in C#?

How Can I Transfer an Event Handler Between Controls in C#?

Linda Hamilton
Release: 2025-01-02 14:51:38
Original
688 people have browsed it

How Can I Transfer an Event Handler Between Controls in C#?

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
Copy after login

Possible Theft Techniques:

  • Direct Transfer: Alas, this seemingly straightforward approach triggers a stern compiler retort.
  • Handler Replication: Copying the event handler and assigning it to multiple controls is doable. However, it's not the sought-after solution in this case.

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template