Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
Previous Versions
.NET Framework 3.0
Class Library
System
EventArgs Class

  Switch on low bandwidth view
EventArgs Class
EventArgs is the base class for classes containing event data.

Namespace: System
Assembly: mscorlib (in mscorlib.dll)

Visual Basic (Declaration)
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class EventArgs
Visual Basic (Usage)
Dim instance As EventArgs
C#
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public class EventArgs
C++
[SerializableAttribute] 
[ComVisibleAttribute(true)] 
public ref class EventArgs
J#
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public class EventArgs
JScript
SerializableAttribute 
ComVisibleAttribute(true) 
public class EventArgs
XAML
Not applicable.

This class contains no event data; it is used by events that do not pass state information to an event handler when an event is raised. If the event handler requires state information, the application must derive a class from this class to hold the data.

For example, the System.AssemblyLoadEventArgs class is used to hold the data for assembly load events, and contains a System.Reflection.Assembly that describes the loaded assembly.

For more information about events, see the EventHandler topic.

The following code sample illustrates the use of EventArgs.

In this sample, FireEventArgs is a set of event arguments derived from EventArgs, and passed to the FireEventHandler when an event is raised by calling ActivateFireAlarm.

Visual Basic
Imports System

 _

' FireEventArgs: a custom event inherited from EventArgs.

Public Class FireEventArgs
   Inherits EventArgs
   
   Public Sub New(room As String, ferocity As Integer)
      Me.room = room
      Me.ferocity = ferocity
   End Sub 'New
   
   ' The fire event will have two pieces of information-- 
   ' 1) Where the fire is, and 2) how "ferocious" it is. 
 
   Public room As String
   Public ferocity As Integer
End Class 'FireEventArgs
 _ 
'end of class FireEventArgs

Public Class FireAlarm
   
   ' Events are handled with delegates, so we must establish a FireEventHandler
   ' as a delegate:

   Delegate Sub FireEventHandler(sender As Object, fe As FireEventArgs)
   
   ' Now, create a public event "FireEvent" whose type is our FireEventHandler delegate.

   Public Event FireEvent As FireEventHandler
   
   
   ' This will be the starting point of our event-- it will create FireEventArgs,
   ' and then raise the event, passing FireEventArgs.

   Public Sub ActivateFireAlarm(room As String, ferocity As Integer)
      
      Dim fireArgs As New FireEventArgs(room, ferocity)
      
      '  Now, raise the event by invoking the delegate. Pass in 
      '  the object that initated the event (Me) as well as FireEventArgs. 
      '  The call must match the signature of FireEventHandler.

      RaiseEvent FireEvent(Me, fireArgs)

   End Sub 'ActivateFireAlarm
End Class 'FireAlarm

' The following event will be the EventHandler.
 
Class FireHandlerClass
   
   
   ' Create a FireAlarm to handle and raise the fire events. 

   Public Sub New(fireAlarm As FireAlarm)
      
      ' Add a delegate containing the ExtinguishFire function to the class'
      ' event so that when FireAlarm is raised, it will subsequently execute 
      ' ExtinguishFire.

      AddHandler fireAlarm.FireEvent, AddressOf ExtinguishFire

   End Sub 'New
   
   
   ' This is the function to be executed when a fire event is raised.
   
   Sub ExtinguishFire(sender As Object, fe As FireEventArgs)
     
      Console.WriteLine() 
      Console.WriteLine("The ExtinguishFire function was called by {0}.", sender.ToString())
      
      ' Now, act in response to the event.

      If fe.ferocity < 2 Then
         Console.WriteLine("This fire in the {0} is no problem.  I'm going to pour some water on it.", fe.room)
      Else
         If fe.ferocity < 5 Then
            Console.WriteLine("Using Fire Extinguisher to put out the fire in the {0}.", fe.room)
         Else
            Console.WriteLine("The fire in the {0} is out of control.  I'm calling the fire department.", fe.room)
         End If
      End If 'end of class FireHandlerClass
   End Sub 'ExtinguishFire
End Class 'FireHandlerClass

Public Class FireEventTest
   
   Public Shared Sub Main()
      
      ' Create an instance of the class that will be raising the event.
      Dim myFireAlarm As New FireAlarm()
      
      ' Create an instance of the class that will be handling the event. Note that 
      ' it receives the class that will fire the event as a parameter. 

     Dim myFireHandler As New FireHandlerClass(myFireAlarm)
        
      ' Now, use the FireAlarm class to raise a few events. 

      myFireAlarm.ActivateFireAlarm("Kitchen", 3)
      myFireAlarm.ActivateFireAlarm("Study", 1)
      myFireAlarm.ActivateFireAlarm("Porch", 5)
      
      Return
   End Sub 'Main 'end of main
End Class 'FireEventTest ' end of FireEventTest
C#
using System;

// FireEventArgs: a custom event inherited from EventArgs.

public class FireEventArgs: EventArgs {
    public FireEventArgs(string room, int ferocity) {
        this.room = room;
        this.ferocity = ferocity;
    }

    // The fire event will have two pieces of information-- 
    // 1) Where the fire is, and 2) how "ferocious" it is.  

    public string room;
    public int ferocity;

}    //end of class FireEventArgs


// Class with a function that creates the eventargs and initiates the event
public class FireAlarm {

    // Events are handled with delegates, so we must establish a FireEventHandler
    // as a delegate:

    public delegate void FireEventHandler(object sender, FireEventArgs fe);

    // Now, create a public event "FireEvent" whose type is our FireEventHandler delegate. 

    public event FireEventHandler FireEvent;    

    // This will be the starting point of our event-- it will create FireEventArgs,
    // and then raise the event, passing FireEventArgs. 

    public void ActivateFireAlarm(string room, int ferocity) {

        FireEventArgs fireArgs = new FireEventArgs(room, ferocity);

        // Now, raise the event by invoking the delegate. Pass in 
        // the object that initated the event (this) as well as FireEventArgs. 
        // The call must match the signature of FireEventHandler.

        FireEvent(this, fireArgs); 
    }
}    // end of class FireAlarm


// Class which handles the event

class FireHandlerClass {

    // Create a FireAlarm to handle and raise the fire events. 

    public FireHandlerClass(FireAlarm fireAlarm)    {

        // Add a delegate containing the ExtinguishFire function to the class'
        // event so that when FireAlarm is raised, it will subsequently execute 
        // ExtinguishFire.

        fireAlarm.FireEvent += new FireAlarm.FireEventHandler(ExtinguishFire);
    }

    // This is the function to be executed when a fire event is raised. 
 
    void ExtinguishFire(object sender, FireEventArgs fe) {

        Console.WriteLine("\nThe ExtinguishFire function was called by {0}.", sender.ToString());

        // Now, act in response to the event.

        if (fe.ferocity < 2)
            Console.WriteLine("This fire in the {0} is no problem.  I'm going to pour some water on it.", fe.room);
        else if (fe.ferocity < 5)
            Console.WriteLine("I'm using FireExtinguisher to put out the fire in the {0}.",  fe.room);
        else 
            Console.WriteLine("The fire in the {0} is out of control.  I'm calling the fire department!", fe.room);
    }
}    //end of class FireHandlerClass

public class FireEventTest {
    public static void Main ()     {    

        // Create an instance of the class that will be firing an event.

        FireAlarm myFireAlarm = new FireAlarm();
        
        // Create an instance of the class that will be handling the event. Note that 
        // it receives the class that will fire the event as a parameter. 

        FireHandlerClass myFireHandler = new FireHandlerClass(myFireAlarm);
        
        //use our class to raise a few events and watch them get handled
        myFireAlarm.ActivateFireAlarm("Kitchen", 3);
        myFireAlarm.ActivateFireAlarm("Study", 1);
        myFireAlarm.ActivateFireAlarm("Porch", 5);
        
        return;

    }    //end of main

}    // end of FireEventTest

C++
using namespace System;

// FireEventArgs: a custom event inherited from EventArgs.
public ref class FireEventArgs: public EventArgs
{
public:
   FireEventArgs( String^ room, int ferocity )
   {
      this->room = room;
      this->ferocity = ferocity;
   }


   // The fire event will have two pieces of information-- 
   // 1) Where the fire is, and 2) how "ferocious" it is.  
   String^ room;
   int ferocity;
};


//end of class FireEventArgs
// Class with a function that creates the eventargs and initiates the event
public ref class FireAlarm
{
public:
   delegate void FireEventHandler(    // Events are handled with delegates, so we must establish a FireEventHandler
   // as a delegate:
   Object^ sender, FireEventArgs^ fe );
   event FireEventHandler^ FireEvent;

   // Now, create a public event "FireEvent" whose type is our FireEventHandler delegate. 
   // This will be the starting point of our event-- it will create FireEventArgs,
   // and then raise the event, passing FireEventArgs. 
   void ActivateFireAlarm( String^ room, int ferocity )
   {
      FireEventArgs^ fireArgs = gcnew FireEventArgs( room,ferocity );
      
      // Now, raise the event by invoking the delegate. Pass in 
      // the object that initated the event (this) as well as FireEventArgs. 
      // The call must match the signature of FireEventHandler.
      FireEvent( this, fireArgs );
   }

};


// end of class FireAlarm
// Class which handles the event
ref class FireHandlerClass
{
public:

   // Create a FireAlarm to handle and raise the fire events. 
   FireHandlerClass( FireAlarm^ fireAlarm )
   {
      
      // Add a delegate containing the ExtinguishFire function to the class'
      // event so that when FireAlarm is raised, it will subsequently execute 
      // ExtinguishFire.
      fireAlarm->FireEvent += gcnew FireAlarm::FireEventHandler( this, &FireHandlerClass::ExtinguishFire );
   }


   // This is the function to be executed when a fire event is raised. 
   void ExtinguishFire( Object^ sender, FireEventArgs^ fe )
   {
      Console::WriteLine( "\nThe ExtinguishFire function was called by {0}.", sender );
      
      // Now, act in response to the event.
      if ( fe->ferocity < 2 )
            Console::WriteLine( "This fire in the {0} is no problem.  I'm going to pour some water on it.", fe->room );
      else
      if ( fe->ferocity < 5 )
            Console::WriteLine( "I'm using FireExtinguisher to put out the fire in the {0}.", fe->room );
      else
            Console::WriteLine( "The fire in the {0} is out of control.  I'm calling the fire department!", fe->room );
   }

};


//end of class FireHandlerClass
int main()
{
   
   // Create an instance of the class that will be firing an event.
   FireAlarm^ myFireAlarm = gcnew FireAlarm;
   
   // Create an instance of the class that will be handling the event. Note that 
   // it receives the class that will fire the event as a parameter. 
   FireHandlerClass^ myFireHandler = gcnew FireHandlerClass( myFireAlarm );
   
   //use our class to raise a few events and watch them get handled
   myFireAlarm->ActivateFireAlarm( "Kitchen", 3 );
   myFireAlarm->ActivateFireAlarm( "Study", 1 );
   myFireAlarm->ActivateFireAlarm( "Porch", 5 );
} //end of main


System.Object
  System.EventArgs
     Derived Classes
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

XNA Framework

Supported in: 1.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Generic Event Arguments      Dwellingbrook   |   Edit   |   Show History

One can tire of writing EventArgs classes for each kind of argument that one wishes to pass to an event handler.

The solution? A generic class for event arguments. This works well because:

  • Your data type is usually already defined for some other purpose.
  • Often (almost always) you can get away with passing only one argument.
  • It works no differently than using any other class derived from EventArgs, except you don't have to write a new one for each data type.

Here is the code:

[C#]
public class EventArg<T> : EventArgs
{
private T eventData;
public EventArg(T data) //constructor
{
eventData = data;
}

public T Data //public property for the argument
{
get { return eventData; }
}
}
Generic Event Arguments Example      Dwellingbrook ... elmarj   |   Edit   |   Show History

The fire alarm example above can be modified to demonstrate the use of the generic EventArg<T> class described previously.

Let's suppose that our fire alarm system has sensors that send us a FireSignal struct with 'room' and 'ferocity' as above. Rather than unpack the FireSignal to create an instance of FireEventArgs, we'll eliminate FireEventArgs and use EventArg<FireSignal> instead. The code below produces identically the same output as the orginal example.

[C#]
  
// FireSignal: a structure for passing information from the fire sensors.
// An EventArgs class for this information would basicly duplicate
// the code that is already here. Instead, we'll use the FireSignal
// struct in the EventArg<T> generic class that was defined previously.
public struct FireSignal
{
public string room;
public int ferocity;
    public FireSignal(string room, int ferocity)
{
this.room = room;
this.ferocity = ferocity;
}
} //end of struct FireSignal
 
// Class with a function that creates the eventargs and initiates the event
public class FireAlarm
{
public delegate void FireEventHandler(object sender, EventArg<FireSignal> fe);
public event FireEventHandler FireEvent;
public void ActivateFireAlarm(FireSignal fireSignal)
{
FireEvent(this, new EventArg<FireSignal>(fireSignal));
}
} // end of class FireAlarm
 
// Class that handles the event
class FireHandlerClass
{
// Create a FireAlarm to handle and raise the fire events.
public FireHandlerClass(FireAlarm fireAlarm)
{
fireAlarm.FireEvent += new FireAlarm.FireEventHandler(ExtinguishFire);
}
// This is the function to be executed when a fire event is raised.
void ExtinguishFire(object sender, EventArg<FireSignal> fe)
{
Console.WriteLine("\nThe ExtinguishFire function was called by {0}.", sender.ToString());
// Now, act in response to the event.
if (fe.data.ferocity < 2)
Console.WriteLine("This fire in the {0} is no problem. I'm going to pour some water on it.", fe.data.room);
else if (fe.data.ferocity < 5)
Console.WriteLine("I'm using FireExtinguisher to put out the fire in the {0}.", fe.data.room);
else
Console.WriteLine("The fire in the {0} is out of control. I'm calling the fire department!", fe.data.room);
}
} //end of class FireHandlerClass
 
public class FireEventTest
{
public static void Main()
{
// Create an instance of the class that will be firing an event.
FireAlarm myFireAlarm = new FireAlarm();
// Create an instance of the class that will be handling the event. Note that
// it receives the class that will fire the event as a parameter.
FireHandlerClass myFireHandler = new FireHandlerClass(myFireAlarm);
//Use our class to raise a few events and watch them get handled
//Simulate receiving signals from the fire sensors and activating
//the corresponding alarm.
FireSignal signal;
signal = new FireSignal("Kitchen", 3);
myFireAlarm.ActivateFireAlarm(signal);
signal = new FireSignal("Study", 1);
myFireAlarm.ActivateFireAlarm(signal);
signal = new FireSignal("Porch", 5);
myFireAlarm.ActivateFireAlarm(signal);
return;
} //end of main
} // end of FireEventTest}
 
// The generic event arguments class (repeated here for reference)
public class EventArg<T> : EventArgs
{
private T eventData;
public EventArg(T data) //constructor
{
eventData = data;
}
public T Data //public property for the argument
{
get { return eventData; }
}
} //End of EventArg<T>
Tags What's this?: Add a tag
Flag as ContentBug
What a pity      David Streeter   |   Edit   |   Show History

What a pity the base System.EventArgs class does not have a property that contains the event name!!

I believe it is more useful to write a routine that handles different events from the same control, rather than a routine that handles the same event from different controls.

-David Streeter

A response:

If you really must do this, then write your monster event handler as a method that takes an extra parameter, such as an enum of whatever you want to name the events. Then call that from all of the normal event handlers, passing in the event name. But this isn't recommended.

Generally we don't write a routine that handles different events for the same control because it violates a basic design rule of having a single purpose for each method, i.e. each method (routine) should encapsulate a single function. Since different events generally represent different functions of a control, they should have different methods to handle them. It is possible to assign the same handler method to several events but if handling the event requires knowing which particular event triggered it, this is probably a bad idea. One can image cases where handling several related events would only require knowing the state of the control, and these would be legitimate cases for handling with a single method.

On the other hand, it is very common to have many similar controls that need identical handling for the same type of event. In this case we write one method that handles the same event for different controls, and we use the Sender parameter to have access to the particular control, to get or set its state.

Can you provide a specific example of something where the general practice does not suffice?

-Dwellingbrook

On a picturebox: Distinguishing between a single click (re-centre) and a click-and-drag (scroll picture). Code to implement this would be much neater if you could handle MouseDown, MouseMove and MouseUp all in the one method.

-David Streeter

Not always necessary to declare an instance of EventArgs      Dwellingbrook   |   Edit   |   Show History

(Originally submitted as a topic for .NET 2.0 by David M. Kean)

You don't need to create an instance of the EventArgs class if you know that your event handlers won't use it. If you have an event that only needs to take an emply EventArgs, simply pass the static (Shared in Visual Basic) field EventArgs.Empty:

[C#]
  
public class Button
{
public event EventHandler Click;
protected virtual
void OnClick(EventArgs e)
{
if (Click != null)
{
Click(this, e);
}
}
private void RaiseClick()
{
OnClick(EventArgs.Empty);
}
}

Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker