Defining an event for a windows forms custom control

c#, custom-controls, visual-studio

Solution

If your event should not provide any additional info (Foo is name of your event):

public event EventHandler Foo;

And raise it this way:

protected virtual void OnFoo()
{
    if (Foo != null)
        Foo(this, EventArgs.Empty);
}

If you need to pass some additional info to event handlers, then create custom arguments class by inheriting from `EvenArgs` class

public class FooEventArgs : EventArgs
{
    public string Message { get; private set; }

    public FooEventArgs(string message)
    {
        Message = message;
    }
}

Declare event this way:

public event EventHandler<FooEventArgs> Foo;

And raise it this way:

protected virtual void OnFoo(string message)
{
   if (Foo != null)
       Foo(this, new FooEventArgs(message));
}

Its good practice to create protected methods for raising events by descendants of class where event is declared. Also good practice to use event naming convention:

- add suffix `-ing` to event name for events which raised before something happened (often you could cancel such events) (e.g. Validating)

- add suffix `-ed` to event name for events which raised after something happened (e.g. Clicked)

As Thorsten stated, good practice to create `virtual` methods for raising events. Its not only allows to raise events from descendants, but also disable event raising, or adding some behavior prior/after event raising.

Problem

I'm working on an form custom control.the control is a MonthCalendar like Visual studio(C#) MonthCalendar control and I want to define an event for my control. How can define a new event for this form custom control?

Original source