Defining an Event in Windows Forms Controls

 

For details about defining custom events, see Handling and Raising Events. If you define an event that does not have any associated data, use the base type for event data, EventArgs, and use EventHandler as the event delegate. All that remains to do is to define an event member and a protected OnEventName method that raises the event.

The following code fragment shows how the FlashTrackBar custom control defines a custom event, ValueChanged. For the complete code for the FlashTrackBar sample, see the How to: Create a Windows Forms Control That Shows Progress.

using System;
using System.Windows.Forms;
using System.Drawing;

public class FlashTrackBar : Control {
   // The event does not have any data, so EventHandler is adequate 
   // as the event delegate.
   private EventHandler onValueChanged;
   // Define the event member using the event keyword.
   // In this case, for efficiency, the event is defined 
   // using the event property construct.
   public event EventHandler ValueChanged {
            add {
                onValueChanged += value;
            }
            remove {
                onValueChanged -= value;
            }
        }
   // The protected method that raises the ValueChanged
   // event when the value has actually 
   // changed. Derived controls can override this method.  
   protected virtual void OnValueChanged(EventArgs e) {
      if (ValueChanged != null) {
         ValueChanged(this, e);
      }
   }
}
Show: