Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

How to: Connect Event Handler Methods to Events

To consume events defined in another class, you must define and register an event handler. The event handler must have the same method signature as the delegate declared for the event. You register your event handler by adding the handler to the event. After you have added your event handler to the event, the method is called whenever the class raises the event.

For a complete sample that illustrates raising and handling events, see How to: Raise and Consume Events.

To add an event handler method for an event

  • Define an event handler method with the same signature as the event delegate.

public class WakeMeUp
    // AlarmRang has the same signature as AlarmEventHandler. 
    internal void AlarmRang(object sender, AlarmEventArgs e)
  1. Create an instance of the delegate, using a reference to the event handler method. When the delegate instance is called, it in turn calls the event handler method.

// Create an instance of WakeMeUp.
WakeMeUp w = new WakeMeUp();

// Instantiate the event delegate.
AlarmEventHandler alhandler = new AlarmEventHandler(w.AlarmRang);
  1. Add the delegate instance to the event. When the event is raised, the delegate instance and its associated event handler method is called.

// Instantiate the event source.
AlarmClock clock = new AlarmClock();

// Add the delegate instance to the event.
clock.Alarm += alhandler;

Community Additions

© 2015 Microsoft