Raising an Event
If you want your class to raise an event, you must provide the following three elements:
A class that provides event data.
An event delegate.
The class that raises the event.
By convention in the .NET Framework, when an event is raised, it passes event data to its event handlers. The event data is provided by the System.EventArgs class or by a class that is derived from it.
Often, an event has no custom data; the fact that the event was fired provides all of the information that event handlers require. In this case, the event can pass an EventArgs object to its handlers. The EventArgs class has only a single member, Empty, that is not inherited from System.Object. It can be used to instantiate a new EventArgs class.
If an event does have custom data, it can pass an instance of a class derived from EventArgs to event handlers. Depending on the precise data the event passes to handlers, you may be able to use an existing event data class in the .NET Framework. For example, if your event handler allows the action associated with the event to be cancelled, you can use the CancelEventArgs class.
When you need to provide custom data to handlers and a existing class is not available, you can define your own event data class. It must derive from System.EventArgs. By convention, this class is named EventNameEventArgs. The following example illustrates such a custom event data class. It defines a class named AlarmEventArgs that provides two items of data to event handlers: the read-only Time property, which indicates when the alarm went off; and the Snooze property, which indicates whether the alarm should go off again after a designated interval or whether future alarms should be cancelled.
public class AlarmEventArgs : EventArgs { private DateTime alarmTime; private bool snoozeOn = true; public AlarmEventArgs(DateTime time) { this.alarmTime = time; } public DateTime Time { get { return this.alarmTime; } } public bool Snooze { get { return this.snoozeOn; } set { this.snoozeOn = value; } } }
An event delegate is used to define the signature of the event. A particular event delegate typically corresponds to a particular event data class. By convention, events in the .NET Framework have the signature EventName(sender, e), where sender is an Object that provides a reference to the class or structure that fired the event, and e is an EventArgs object or an object derived from EventArgs that provides event data. The delegate definition then typically takes the form EventNameHandler(sender, e).
If you are using an event data class that is already defined in the .NET Framework class library or in a third-party library, it is likely that a corresponding event delegate is also defined in that library. For example, the EventHandler delegate can be used along with the EventArgs class. Similarly, the CancelEventHandler delegate can be used along with the CancelEventArgs class.
If you define a custom event data class, you can also define a custom delegate to define the event signature, or you can use the generic Action<T1, T2> delegate.
The following example defines an event delegate named AlarmEventHandler.
The class that raises the event must provide the event declaration and define a method that raises the event. In addition, it must provide some logic to raise the event in a class property or method.
You define an event member in your class using the event keyword in C# or the Event statement in Visual Basic. When the compiler encounters an event declaration in your class, it creates a private member such as:
private EventNameHandler eh = null;
The compiler also creates the two public methods, add_EventName and remove_EventName. These methods are event hooks that allow delegates to be combined or removed from the event delegate eh. The details are hidden from the programmer.
Note |
|---|
In languages other than C# and Visual Basic 2005, the compiler might not automatically generate the code corresponding to an event member, and you might have to explicitly define the event hooks and the private delegate field. |
The following example declares an event named AlarmEvent. It is excerpted from the example for a class named Alarm whose complete source code is shown below. Note that it has the signature of the AlarmEventHandler delegate.
Once you have defined your event implementation, you must determine when to raise the event. You raise the event by calling the protected OnEventName method in the class that defined the event, or in a derived class. The OnEventNamemethod then raises the event.
Note |
|---|
The protected OnEventNamemethod also allows derived classes to override the event without attaching a delegate to it. A derived class must always call the OnEventNamemethod of the base class to ensure that registered delegates receive the event. |
The following example defines the OnAlarmEvent method, which is responsible for raising the AlarmEvent event.
The following example defines a method named Set that contains the logic to fire the event by calling the OnAlarmEvent method. If the hours and the minutes of the alarm time equal the hours and minutes of the current time, the Set method instantiates an AlarmEventArgs object and provides it with the time that the alarm went off. After the event handlers execute, it checks the value of the Snooze property. If Snooze is false, no more alarm events are to be raised, so the Set method can end. If Snooze is true, the time the alarm is to go off is incremented by the value of the Interval property.
public void Set() { while (true) { System.Threading.Thread.Sleep(2000); DateTime currentTime = DateTime.Now; // Test whether it is time for the alarm to go off. if (currentTime.Hour == alarmTime.Hour && currentTime.Minute == alarmTime.Minute) { AlarmEventArgs args = new AlarmEventArgs(currentTime); OnAlarmEvent(args); if (! args.Snooze) return; else this.alarmTime = this.alarmTime.AddMinutes(this.interval); } } }
The following example includes all of the source code for the Alarm class.
public class Alarm { private DateTime alarmTime; private int interval = 10; public event AlarmEventHandler AlarmEvent; public Alarm(DateTime time) : this(time, 10) { } public Alarm(DateTime time, int interval) { this.alarmTime = time; this.interval = interval; } public void Set() { while (true) { System.Threading.Thread.Sleep(2000); DateTime currentTime = DateTime.Now; // Test whether it is time for the alarm to go off. if (currentTime.Hour == alarmTime.Hour && currentTime.Minute == alarmTime.Minute) { AlarmEventArgs args = new AlarmEventArgs(currentTime); OnAlarmEvent(args); if (! args.Snooze) return; else this.alarmTime = this.alarmTime.AddMinutes(this.interval); } } } protected void OnAlarmEvent(AlarmEventArgs e) { AlarmEvent(this, e); } }
There can be two things.
1. How to raise an event in your custom control.
This is to expose events your custom control supports. When there is user interaction the custom control, it can raise an event.
This is what this document is for.
2. How to raise an event of a control programmatically or from other part of the code.
For example, when you press "Increase Value" button which sits next to a TrackBar control, you want to change the slider of the TrackBar and thus change its button. It's like to move your mouse by holding the slider thumb.
It's about how to raise "Scroll" event of that TrackBar.
This document is about the 1st one not the 2nd one.
This shows the fundamental problem of MSDN documentation. It's not quite clear what it is for from its explanation. People need to read from the first to the end.
- 3/19/2012
- JongAm Park
protectedvoid OnAlarm(AlarmEventArgs e) { if (Alarm != null) { Alarm(this, e); } }
- 7/26/2011
- jbtibo
- 7/26/2011
- jbtibo
Following requires a correction
When you need to provide custom data to handlers and a existing class is not available, you can define your own event data class. It must derive from System.EventArgs. By convention, this class is named EventNameEventArgs.
If we name the event argument class this manner the word Event will appear twice. To avoid this there are two ways to do it.
1. When you need to provide custom data to handlers and a existing class is not available, you can define your own event data class. It must derive from System.EventArgs. By convention, this class is named
EventNameArgs.
2.When you need to provide custom data to handlers and a existing class is not available, you can define your own event data class. It must derive from System.EventArgs. By convention, this class is named
ClassNameEventArgs.
Choice is yours. I prefer method 1 above
Rohan Thalagala -- Sri Lanka
Yes, the choice is always yours. But this is about a Microsoft recommended convention.
Therefore, the original description by Microsoft is correct. The correct convention is EventNameEventArgs. Thsi convention is followed throughout .Net.
So, in the Alarm example, the EventName is Alarm. And so the event data class, if you correctly follow the convention, is AlarmEventArgs (exactly as it was in the example by MS)
- 6/28/2010
- Rohan Thalagala
- 7/15/2011
- psychorat
The Following line should be corrected
When you need to provide custom data to handlers and a existing class is not available, you can define your own event data class. It must derive from System.EventArgs. By convention, this class is named EventNameEventArgs
The correct way is as follows....
When you need to provide custom data to handlers and a existing class is not available, you can define your own event data class. It must derive from System.EventArgs. By convention, this class is named
ClassNameEventArgs
Otherwise the word Event will appear twice.
- 6/28/2010
- Rohan Thalagala
Step 1. Event data class named EventNameArgs. Correct, I guess, to name it EventNameEventArgs
Step 4. Method that raises the event in examples code defined as protected virtual,
but in full example in the end of the article this method defined as protected (not protected virtual).
What is conventional approach?
- 4/24/2010
- ADVSDG
Note