Click here to Skip to main content
15,867,141 members
Articles / Desktop Programming / Windows Forms

How to copy event handlers from one control to another at runtime

Rate me:
Please Sign up or sign in to vote.
4.96/5 (11 votes)
1 Jan 2012CPOL4 min read 58K   2.4K   22   15
This article will show you how to copy event handlers from one control to another at run time using dirty tricks and .NET Reflection.

Introduction

Today at work, one of my partners in crime was working on a crazy customer requirement and asked me if I think that it would be possible to copy event handlers from one control to another at run time and keep things working correctly. I said yes, I think it’s possible and must be easy too, let’s take a look…

After a couple of minutes, we figured out that the Control class doesn't expose any public method or property to get access to the collection of delegates attached to the control’s events.

I did a fair amount of web research and found a lot of partial solutions but none that fit our needs. So I decided to roll my own solution, post it, and may be help some who is facing the very same problem.

Normally when we are working with events, we hook them up with handlers, writing a piece of code like this:

C#
textBox1.TextChanged += (s, e) => MessageBox.Show("Hi there from handler 1");

It’s also common to attach more than one handler to the same event:

C#
textBox1.TextChanged += (s, e) => MessageBox.Show("Hi there from handler 1");
textBox1.TextChanged += (s, e) => MessageBox.Show("Hi there from handler 2");
//*(I’m using lambdas for shortness)

The requirement is to provide some mechanism to create a new textbox at runtime (let's say textBox2) and attach to it the list of handlers that had been attached to the textBox1 at design time. (We also need to destroy textBox1, but this is not the point.)

In this article, I’m assuming that you are familiar with events and you know the basics of how they work, so I’m not going to cover in deep the “events machinery” in .NET. However, in order to move on, we need to review how handlers are (internally) attached to or detached from an event in .NET.

The snippet above is from the (decompiled) Control class of the .NET Framework:

C#
private static readonly object EventText = new object();

public event EventHandler TextChanged {
    add { 
        Events.AddHandler(EventText, value); 
    }
    remove { 
        Events.RemoveHandler(EventText, value);
    }
}

Here, EventText is the field (key) that the Control class uses to point to a list of handlers (delegates) to a given event, in this case TextChanged.

So when we write:

C#
textBox1.TextChanged += some delegate…

Internally, we are adding that delegate to the list of handlers.

C#
add { 
    Events.AddHandler(EventText, value); 
}

Now that we understand the very basics about how the process of adding/removing event handlers internally works, we can imagine that if somehow we can get the value of the property Events and know the correct key, we may be able to pull off the collection of delegates attached to a specified event and iterate through that collection and, hopefully, get the delegates and accomplish our mission ;)

This solution makes heavy use of Reflection, mainly because as I said before, there is no public API to work against it. For instance, the property Events is marked as protected in the Control class and there isn't another way to access it (unless you are using extended controls or the like, but this isn’t our case).

The current implementation only works with events declared on the Control class. You can get the full list of supported events using .NET Reflector or a similar tool. If the event that you are looking for is not supported by the current implementation, you can make it work by modifying a few lines of code (more on this later).

First of all, we need to get the list of handlers attached to an event and this handy method take cares of that.

C#
public Dictionary<string, Dictionary<object, Delegate[]>> GetHandlersFrom(Control ctrl) {
    var ctrlEventsCollection = (EventHandlerList)typeof(Control)
    .GetProperty("Events", BF.GetProperty | BF.NonPublic | BF.Instance)
    .GetValue(ctrl, null);
           
    var headInfo = typeof(EventHandlerList)
    .GetField("head", BF.Instance | BF.NonPublic);
    var handlers = BuildList(headInfo, ctrlEventsCollection);
 
            var eventName = GetEventNameFromKey(ctrl, handlers.First().Key);
 
            //TODO: use key value pair.
            var result = new Dictionary<string, Dictionary<object, 
                         Delegate[]>> { { eventName, handlers } };
 
            return result;
}

Now we have the delegates but we don't know (yet) which is the event in the new control that we have to hookup. At this poin,t we’re going to use a dictionary that contains some sort of map between the event’s name and the corresponding field in the Control class. Based on the key that we already have and using some Reflection magic, we can attach those delegates to the correct event in our brand new control.

C#
//The mapping
_keyEventNameMapping = new Dictionary<string,>{
                {"EventAutoSizeChanged", "AutoSizeChanged"},
                {"EventBackColor", "BackColorChanged"},
                //etc, etc…

How can I make it work if the event that I’m interested in is not defined in the Control class?

Easy, if you want to extend this solution to work with events that are not defined in the Control class. First, add the map in the _keyEventNameMapping field and then modify this line in the CopyTo extension method:

C#
//Instead of Control use the class you need
var info = typeof(Control).GetField(innerKeyFieldName,
          BF.GetField | BF.Static | BF.NonPublic | BF.DeclaredOnly);

Running the sample application

Once you download the sample app, run it and you’ll see a form with two textboxes and a button. If you enter text in the textbox labeled Source, you’ll notice that two events will fire and the handlers attached to those events will show a message. Nothing should happen if you enter text in the textbox labeled Destination.

Now, press the button named “Copy event handlers” and enter some text in the textbox labeled Destination. If all goes well, you should see the messages from the event handlers attached to the Source textbox now attached to the Destination textbox.

Using the code

For copying handlers from one control to another, you just need those two lines of code:

C#
var _copyHelper = new CopyEventHandlers();
_copyHelper.GetHandlersFrom(textBox1).CopyTo(textBox2);

If you have any questions about using the code, don’t hesitate to contact me, I’ll be glad to help.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionIt woks but I believe that these three lines do more: Pin
discharge9-Dec-15 22:02
discharge9-Dec-15 22:02 
SuggestionSimpler way to accomplish the task Pin
Trif_cz15-May-14 19:52
Trif_cz15-May-14 19:52 
QuestionHow to copy event handlers from one control to another at runtime Pin
Member 85954336-Feb-14 23:05
Member 85954336-Feb-14 23:05 
AnswerRe: How to copy event handlers from one control to another at runtime Pin
Alejandro Miralles10-Feb-14 13:13
Alejandro Miralles10-Feb-14 13:13 
QuestionWorking On Net.Cf Pin
arachnida8-May-13 3:43
arachnida8-May-13 3:43 
AnswerRe: Working On Net.Cf Pin
Alejandro Miralles10-Feb-14 13:26
Alejandro Miralles10-Feb-14 13:26 
QuestionCopying when no events exist Pin
Jonny007-MKD22-Apr-13 20:26
Jonny007-MKD22-Apr-13 20:26 
AnswerRe: Copying when no events exist Pin
Alejandro Miralles10-Feb-14 13:30
Alejandro Miralles10-Feb-14 13:30 
QuestionExcelente Pin
leonardo brambilla31-Jan-12 8:51
leonardo brambilla31-Jan-12 8:51 
AnswerRe: Excelente Pin
Alejandro Miralles1-Feb-12 1:38
Alejandro Miralles1-Feb-12 1:38 
GeneralMy vote of 5 Pin
gz.damian4-Jan-12 2:43
gz.damian4-Jan-12 2:43 
QuestionGreat Job Alejandro! Pin
Tom Clement2-Jan-12 6:55
professionalTom Clement2-Jan-12 6:55 
Gave you a 5. Thanks for sharing with the community.
Tom Clement
Serena Software, Inc.
www.serena.com

articles[^]

AnswerRe: Great Job Alejandro! Pin
Alejandro Miralles3-Jan-12 1:16
Alejandro Miralles3-Jan-12 1:16 
GeneralMy vote of 5 Pin
maq_rohit1-Jan-12 17:43
professionalmaq_rohit1-Jan-12 17:43 
GeneralRe: My vote of 5 Pin
Alejandro Miralles2-Jan-12 3:09
Alejandro Miralles2-Jan-12 3:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.