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:
-
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.
-
protected virtual void OnMyEvent(EventArgs e) {
-
if(MyEvent != null) {
-
MyEvent(this, e);
-
}
-
}
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.
-
MyVariable = newValue;
-
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:
-
MyEventClass.MyEvent += new EventHandler(MyEventHandler);
-
protected virtual void MyEventHandler(object sender, EventArgs e) {
-
// handle event
-
}
References:
C# and VB events links on the MSDN
Declaring, Raising and Handling events MSDN tutorial
Code Project example

July 24th, 2008 at 8:47 am
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);
}
}