Posted: 6 years ago

Filed under: .NET

Tagged with: c# controls delegates events

Follow comments

Raising custom events in C#

First you need to declare an event in the class that’s going to raise the event. This is just like declaring a normal variable:

  1. public event EventHandler MyEvent;

Then you need a method that’s going to be called to raise the event. This goes into the same class that you just declared the event in.

  1. protected virtual void OnMyEvent(EventArgs e) {
  2.     if(MyEvent != null) {
  3.         MyEvent(this, e);
  4.     }
  5. }

In the code where the event actually happens (say the code where a certain variable gets updated), you need to actually raise the event by calling the method we just created.

  1. MyVariable = newValue;
  2. OnMyEvent(EventArgs.Empty);

Then in the class that wants to listen for the event, you just register for it like you’d register for any of the built-in events:

  1. MyEventClass.MyEvent += new EventHandler(MyEventHandler);
  1. protected virtual void MyEventHandler(object sender, EventArgs e) {
  2.     // handle event
  3. }

References:
C# and VB events links on the MSDN
Declaring, Raising and Handling events MSDN tutorial
Code Project example

Comments

  1. NT Says:

    You can also do something like that:
    (Assuming you want to submit text from a textbox when enter is hit and this triggers the submit button)

    private void KeyDownTextBox(object sender, System.Windows.Input.KeyEventArgs e)
    {

    if(e.Key == Key.Enter)
    if (InputTextBox.Text.Length != 0)
    {
    MouseButtonEventArgs mbea = new MouseButtonEventArgs(Mouse.PrimaryDevice, 0, MouseButton.Left);
    mbea.RoutedEvent = Mouse.MouseDownEvent;
    SubmitButton.RaiseEvent(mbea);
    }
    }

Leave a Reply