Information Technology Reference
In-Depth Information
Standard Event Usage
GUI programming is event driven, which means that while the program is running, it can be
interrupted at any time by events such as button clicks, key presses, or system timers. When
this happens, the program needs to handle the event and then continue on its course.
Clearly, this asynchronous handling of program events is the perfect situation to use C#
events. Windows GUI programming uses events so extensively that there is a standard .NET
Framework pattern for using them, which you are strongly encouraged to follow.
The foundation of the standard pattern for event usage is the EventHandler delegate type,
which is declared in the System namespace. The declaration of the EventHandler delegate type
is shown in the following code.
￿
The first parameter is meant to hold a reference to the object that raised the event. It is
of type object and can, therefore, match any instance of any type.
￿
The second parameter is meant to hold state information of whatever type is appropri-
ate for the application.
The return type is void .
￿
public delegate void EventHandler(object sender, EventArgs e);
Using the EventArgs Class
The second parameter in the EventHandler delegate type is an object of class EventArgs , which
is declared in the System namespace. You might be tempted to think that, since the second
parameter is meant for passing data, an EventArgs class object would be able to store data of
some sort. You would be wrong.
￿The EventArgs class is designed to carry no data. It is used for event handlers that do not
need to pass data—and is generally ignored by them.
If you want to pass data, you must declare a class derived from EventArgs , with the
appropriate fields to hold the data you want to pass.
￿
Even though the EventArgs class does not actually pass data, it is an important part of the
pattern of using the EventHandler delegate. Class object and class EventArgs are the base
classes of whatever actual types are used as the parameters. This allows EventHandler to pro-
vide a signature that is the lowest common denominator for all events and event handlers,
allowing them to have exactly two parameters, rather than having different signatures for
each case.
Passing Data by Extending EventArgs
To pass data in the second parameter of your event handler, and adhere to the standard con-
ventions, you need to declare a custom class derived from EventArgs that can store the data
you need passed. The name of the class should end in EventArgs . For example, the following
code declares a custom class that can store a string in a field called Message .
Search WWH ::




Custom Search