Sunday, November 7, 2010

Programmatically invoke an event handler for a control

To test the behavior of a custom Windows Forms button control I had created,  I had to trigger the Click event handler from code. There are multiple ways to achieve this, but I choose to combine a helper class with some convention based reflection. 
I created a static class UIHelper with the following method:
   1:  public static void TriggerEvent(Object targetObject, string eventName, EventArgs e) 
   2:  { 
   3:     String methodName = "On" + eventName; 
   4:   
   5:     MethodInfo mi = targetObject.GetType().GetMethod( 
   6:           methodName,  
   7:           BindingFlags.Instance | BindingFlags.NonPublic); 
   8:   
   9:     if (mi == null) 
  10:        throw new ArgumentException("Cannot find event named "+methodName); 
  11:   
  12:     mi.Invoke(targetObject, new object[] { e }); 
  13:  } 

In this code I took advantage of the fact that by convention event handlers are internally called by a protected method called On[EventName]. 
An example:   a Click event is triggered by the OnClick method. 

The following code will trigger the event:

   1:  UIHelper.TriggerEvent(btnTest, "Click", EventArgs.Empty()); 

No comments: