C# Custom Control Events: Define & Trigger

In C#, you can define custom control events by following these steps:

  1. Begin by creating a custom control class that inherits from the Control class or another suitable base control class. For example:
public class CustomControl : Control
{
    // 事件定义
    public event EventHandler CustomEvent;

    // 事件触发方法
    protected virtual void OnCustomEvent(EventArgs e)
    {
        CustomEvent?.Invoke(this, e);
    }
}
  1. In a custom control class, defining the event that needs to be triggered usually involves using the EventHandler delegate as the event type, for example:
public event EventHandler CustomEvent;
  1. At the appropriate time, such as when the user clicks on the control, invoke the event trigger method. For example:
protected override void OnClick(EventArgs e)
{
    base.OnClick(e);
    OnCustomEvent(e);
}
  1. In the code where custom controls are being used, subscribe to events and handle the logic triggered by the events, such as:
CustomControl customControl = new CustomControl();
customControl.CustomEvent += CustomEventHandler;

private void CustomEventHandler(object sender, EventArgs e)
{
    // 处理事件逻辑
}

By following the steps above, you can define and use events for custom controls.

bannerAds