SoFunction
Updated on 2025-03-07

C# custom events and usage examples

This article describes C# custom events and usage. Share it for your reference. The specific analysis is as follows:

Events are an important part of C#, and there is a demo example of custom events on MSDN. I was a little dizzy after watching it for a long time, so I created a new winform project and added a button, then found the program to be called, and compared it to make a similar example, and then I understood. Sometimes reading code comes faster than reading documents.
So it is still the same principle, and what you do is not rare.

using System;
namespace TestEventArgs
{
 /// <summary>
 /// This class corresponds to EventArgs, for comparison learning. /// Add two contents: info1, info2. /// </summary>
 public class MyEventArgs : EventArgs
 {
  private String info1;
  private UInt32 info2;
  public MyEventArgs(String info1, UInt32 info2)
  {
   this.info1 = info1;
   this.info2 = info2;
  }
  public String Info1
  {
   get { return this.info1; }
   set { this.info1 = value; }
  }
  public UInt32 Info2
  {
   get { return this.info2; }
   set { this.info2 = value; }
  }
 }
 /// <summary>
 /// Simulation Button Button /// </summary>
 public class MyButton
 {
  public delegate void MyEvnetHandler(object sender, MyEventArgs e);
  /// <summary>
  /// The number of times the button clicks counter  /// </summary>
  public static UInt32 clicked_num = 0;
  public event MyEvnetHandler MyClick;
  public void trigger()
  {
   MyEventArgs arg = new MyEventArgs((), ++clicked_num);
   MyClick(this, arg);
  }
 }
 /// <summary>
 /// Simulated Form /// </summary>
 public class MyForm
 {
  public MyButton Button;
  public MyForm()
  {
   Button = new MyButton();
   Button.MyClick += new (this.button_Clicked);
  }
  public void button_Clicked(object sender, MyEventArgs e)
  {
   ("button clicked(sender is:" + () + "; info1 = "
    + e.Info1 + "; info2 = " + e.Info2);
  }
 }
 class Program
 {
  static void Main(string[] args)
  {
   MyForm Form = new MyForm();
   for (int i = 0; i < 10; i++ )
   {
    Form.Button.trigger();
    (500);
   }
   ("Press any key to continue...");
   ();
  }
 }
}

I hope this article will be helpful to everyone's C# programming.