Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could use reflection, but it's going to be slightly tricky because of the various event handler signatures involved. Basically you'd have to get the <code>EventInfo</code> for each event in the type, and use the <a href="http://msdn.microsoft.com/en-us/library/system.reflection.eventinfo.eventhandlertype.aspx" rel="nofollow noreferrer"><code>EventHandlerType</code></a> property to work out what delegate type to create before calling <a href="http://msdn.microsoft.com/en-us/library/system.reflection.eventinfo.addeventhandler.aspx" rel="nofollow noreferrer"><code>AddEventHandler</code></a>. <code>Delegate.CreateDelegate</code> works for everything that follows the normal event handler pattern though... </p> <p>Here's a sample app. Note that it's not doing any checking - if you give it something with a "non-standard" event it will throw an exception. You could fairly easily use reflection to print out the event args too.</p> <pre><code>using System; using System.Drawing; using System.Windows.Forms; using System.Reflection; namespace ConsoleApp { class Program { [STAThread] static void Main(string[] args) { Form form = new Form { Size = new Size(400, 200) }; Button button = new Button { Text = "Click me" }; form.Controls.Add(button); EventSubscriber.SubscribeAll(button); Application.Run(form); } } class EventSubscriber { private static readonly MethodInfo HandleMethod = typeof(EventSubscriber) .GetMethod("HandleEvent", BindingFlags.Instance | BindingFlags.NonPublic); private readonly EventInfo evt; private EventSubscriber(EventInfo evt) { this.evt = evt; } private void HandleEvent(object sender, EventArgs args) { Console.WriteLine("Event {0} fired", evt.Name); } private void Subscribe(object target) { Delegate handler = Delegate.CreateDelegate( evt.EventHandlerType, this, HandleMethod); evt.AddEventHandler(target, handler); } public static void SubscribeAll(object target) { foreach (EventInfo evt in target.GetType().GetEvents()) { EventSubscriber subscriber = new EventSubscriber(evt); subscriber.Subscribe(target); } } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload