Skip to main content

How to copy event handlers from one control to another

Today at work, one of my partners in crime were working on a crazy customer requirement and ask me if I think that would be possible to copy event handlers from one control to another at run time and keeps 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 figure 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 decide to roll my own solution, post it, and may 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:

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:
 
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 provide some mechanism to create a new textbox  at runtime (let 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 post I’m assuming that you are familiar with events and you know the basic 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:

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 a list of handlers (delegates) to a given event, in this case “TextChanged”.

So when we write:
textBox1.TextChanged += some delegate…
Internally, we are adding that delegate to the list of handlers. 
    add { 
        Events.AddHandler(EventText, value); 
    }
 
Now that we understand the very basics about how internally works the process of add/remove event handlers, we can imagine that if somehow we can get the value of the property “Events” and know the correct key, we may able to pull off the collection of delegates attached to a specified event and iterating thru that collection, hopefully, get the delegates and accomplish our mission ;)
 
This solution makes heavily use 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 a 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.
 
public Dictionary<stringDictionary<objectDelegate[]>> 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); 
    var result = new Dictionary<stringDictionary<objectDelegate[]>> 
        {{
            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 point 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.
 
//The mapping
_keyEventNameMapping = new Dictionary<stringstring>{
                {"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
*  Add the map in the _keyEventNameMapping field
* Modify this line in the CopyTo extension method
 
//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 enters some text in the textbox labeled destination. If all went well, you should be seen 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.
 
var _copyHelper = new CopyEventHandlers();
_copyHelper.GetHandlersFrom(textBox1).CopyTo(textBox2);
 


Download Source
Download Sample App
If you have any question about using the code, don’t hesitate con contact me, I’ll be glad to help.

Comments

Popular posts from this blog

Migrating an ASP.NET MVC 4 app from Azure websites to WinHost

About a week ago I've to migrate an ASP.NET MVC 4/EF5 application from Azure websites to WinHost. While the process was really smooth, there were some caveats related to database connections that I want to share with you. Create and setup the ftp profile on VS and configure the connection string was really easy, WinHost provide you those values and there is nothing special here. But once you deploy your website and try to see it online, you may get the “yellow screen of dead” with the message: "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)" Assuming you wrote the connection string properly, this happens because you cannot use the default connection name in your web.c...

How to show excel files inside the .NET Webbrowser Control

If you are reading this, chances are you been banging your head against the wall for a couple of hours (or even days) trying to show excel files inside the WinForms webbrowser control. Possible reasons you ended up in here: You had working code that got broke after upgrading from Win 7. Your code doesn’t work the same way between machines running different (newer) versions of IE. A download box pops up every time your app tries to show an excel file inside the webbrowser control (you wanna show the actual content). You just have no clue on how to get excel working into the .NET embedded webbrowser control. You are trying to implement IInternetSecurityManager and don’t know where to start. (Or how don’t know how to delegate calls to your security manager). Among many other, maybe….. Yes, COM is a PITA, so is ActiveX and IE (Embedded or full for that matter). And no, showing excel files inside the webbrowser control shouldn’t be that hard, but sometimes we have...

How to replace text with images on Word documents using C#

This post it’s a reply to a question I got from a previous post that shows how to work with Word templates from C# code . If you haven’t read it, I recommend to do so because I’m not going into details here. But basically it was about how to create a Word document from a template and perform same text manipulation. So, the question from Marcel Kieboom  was “Do you know if it would be also possible to replace one of the words with an image which is locally stored?” The answer is yes, and this is how you can do that. Based on the same convention I had used in the previous post, I should have a template like this: What I’m trying to do here is replace the text [angus-young] for an actual pic of Angus. The technique I’m using it’s pretty common on web sites and basically consist in have an image with a matching name for each keyword I want to replace and then create the image path dynamically. This is the C# code to do that. * When I execute t...