Reflection Question: Determining and invoking a Control's event handlers

  • Thread starter Thread starter Ben Fidge
  • Start date Start date
B

Ben Fidge

Hi

Is it possible, using Reflection, to determine at runtime the method(s) that
are provided as handler for a given controls events?

Also, once discovered, is it possible to manually invoke these methods?

For example, suppose I have a ImageButton on a webform that has an on click
handler associated. I would like to be able to discover the name of the
event handling method(s) that handle this event, and manually invoke them.

Kind regards

Ben
 
Ben,
Is it possible, using Reflection, to determine at runtime the method(s) that
are provided as handler for a given controls events?

Only by reflecting on private members, and doing that on code you
don't control is asking for trouble, since it can easily break in the
future.



Mattias
 
Hi Mattias,

Do you have an example of how to do this this, or know where I can find one?

Kind regards

Ben
 
Ben,
Do you have an example of how to do this this, or know where I can find one?

using System;
using System.Reflection;

delegate void FooEventHandler();

class Events
{
public event FooEventHandler Foo;
}

class Test
{
static void Handler1() { Console.WriteLine( "Handler1" ); }
static void Handler2() { Console.WriteLine( "Handler2" ); }

static void Main()
{
Events e = new Events();
e.Foo += new FooEventHandler(Handler1);
e.Foo += new FooEventHandler(Handler2);

Delegate d = (Delegate)e.GetType().GetField("Foo",
BindingFlags.NonPublic|BindingFlags.Instance).GetValue(e);
foreach ( FooEventHandler f in d.GetInvocationList() )
f();
}
}

Now this assumes that the underlying delegate field is named the same
as the event (Foo in this case). That's not always true, and there's
no way to get the field name from the event name. There may not even
be a single underlying delegate field for each event.



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top