| |
|
| |
How to Create a Custom EventExplains how to create custom events and handlers in C#. General Example
class Thrower
{
// Declare an event. The first parameter is the
// name of the delegate type for methods that handle
// the event. The second name is the event name.
public event EventDelegate EventName;
// Declare the delegate for the handler. In this simple example,
// the only argument is a string. If the arguments are more complex,
// it's probably better to create a class: EventNameArgs
public delegate void EventDelegate (string argString);
// Raise the event when appropriate. Make sure to check
// for null or else it'll fail if there are no subscribers.
// If the event is raised from a lot of places, or requires
// an EventArgs class, it's usually best to create a helper
// method to build and send the event.
public void SomeMethod()
{
if (EventName!= null)
{
EventName("hello");
}
}
}
class Catcher
{
// Subscribe to the event. This requires creating a
// new delegate instance.
public Catcher()
{
myThrower.EventName += new Thrower.EventDelegate(EventHandler);
}
// Implement the event handler. Prototype must match
// the prototype for EventDelegate.
void EventHandler(string argString)
{
}
}
Specific Example
class Remote
{
public event CriticalErrorHandler CriticalErrorEvent;
public delegate void CriticalErrorHandler(Exception exception);
public void SomeMethod(Exception exception)
{
if (CriticalErrorEvent != null)
{
CriticalErrorEvent(exception);
}
}
}
class MainForm
{
public MainForm()
{
g_remote.CriticalErrorEvent += new Remote.CriticalErrorHandler(HandleCriticalError);
}
void HandleCriticalError(Exception exception)
{
MessageBox.Show("EXCEPTION! " + exception.ToString());
}
}
| |
|
All content copyright 1996-2008 by Linda Naughton O'Meara unless otherwise noted.
Shadowrun is a copyright and trademark of WizKids, LLC.
Earthdawn is a copyright and trademark of FASA Corporation.
Crimson Skies is a copyright and trademark of Microsoft Corporation.
Babylon 5 is a copyright and trademark of Time Warner Entertainment.
Battlestar Galactica is a copyright of Sci Fi / Universal.
Any use of characters, names, places, etc. from these systems is done with the greatest respect for their creators, and is not intended as a challenge to any copyrights or trademarks.
| |