Home > Backend Development > C++ > Can Event Handlers Be Transferred Between Controls Using Reflection?

Can Event Handlers Be Transferred Between Controls Using Reflection?

Mary-Kate Olsen
Release: 2024-12-31 11:18:15
Original
152 people have browsed it

Can Event Handlers Be Transferred Between Controls Using Reflection?

Can Event Handlers Be Transferred Between Controls?

Question:

Is it conceivable to "steal" an event handler associated with one control and assign it to another?

Answer:

Yes, it is possible with a caveat: reflection is necessary. Many relevant members are concealed as private or internal.

Implementation:

Create a new Windows Forms project and place two buttons on its form. Then, utilize the following code:

using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Reflection;

namespace WindowsFormsApplication1 {
  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
      button1.Click += new EventHandler(button1_Click);

      // Get secret click event key
      FieldInfo eventClick = typeof(Control).GetField("EventClick", BindingFlags.NonPublic | BindingFlags.Static);
      object secret = eventClick.GetValue(null);

      // Retrieve the click event
      PropertyInfo eventsProp = typeof(Component).GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
      EventHandlerList events = (EventHandlerList)eventsProp.GetValue(button1, null);
      Delegate click = events[secret];

      // Remove it from button1, add it to button2
      events.RemoveHandler(secret, click);
      events = (EventHandlerList)eventsProp.GetValue(button2, null);
      events.AddHandler(secret, click);
    }

    void button1_Click(object sender, EventArgs e) {
      MessageBox.Show("Yada");
    }
  }
}
Copy after login

Note: This demonstrates how Microsoft restricts access to critical methods for security reasons.

The above is the detailed content of Can Event Handlers Be Transferred Between Controls Using Reflection?. 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