Techie Talks

Friday, April 28, 2006

Creating custom events for dum(m)i(e)s

Purpose: To explain the process of creating and handling custom events.
Steps:

1. Create a new class that extends the EventArgs class
e.g.:

public class DataLockReleasedEventArgs : EventArgs
{
//Add extra properties and construtors
}

2. Define the handler delegate
e.g.:

public delegate void DataLockReleasedEventHandler(object o, DataLockReleasedEventArgs e);

3. In the class that will be generating the event, define the event
e.g.:

public event DataLockReleasedEventHandler DataLockReleased;

4. In the class that will be generating the event, create the "On" method (normally protected)
e.g.:

protected static void OnDataLockReleased(DataLockReleasedEventArgs e)
{
if(DataLockReleased != null)
DataLockReleased(new object(), e); //Instead of new object, pass a meaningful object
}

5. In the class that will be generating the event, generate the event when appropriate
e.g.:

public void EventGenerationMethod(...)
{
...
...
DataLockReleasedEventArgs dlrEventArgs = new DataLockReleasedEventArgs(); //Use appr constr
//Fill in the eventargs properties as necessary
OnDataLockReleased(dlrEventArgs);
...
...
}

6. In the class that will be receiving the events, subscribe to the event, usually during the creation of the event defining class's object
e.g.:

public void CreationMethod()
{
EventDefiningClass evDefClass = new EventDefiningClass();
evDefClass.DataLockReleased += new DataLockReleasedEventHandler(evDefClass_DataLockReleased);
}

7. In the class that will be receiving the events, define the event handling method
e.g.:

void evDefClass_DataLockReleased(object o, DataLockReleasedEventArgs e)
{
//Handle the event
}

0 Comments:

Post a Comment

<< Home