A .NET-compatible event : event « GUI Windows Forms « C# / CSharp Tutorial






using System; 
 
// Derive a class from EventArgs. 
class MyEventArgs : EventArgs { 
  public int eventnum; 
} 
 
// Declare a delegate for an event.  
delegate void MyEventHandler(object source, MyEventArgs arg); 
 
// Declare an event class. 
class MyEvent { 
  static int count = 0; 
 
  public event MyEventHandler SomeEvent; 
 
  // This fires SomeEvent. 
  public void OnSomeEvent() { 
    MyEventArgs arg = new MyEventArgs(); 
 
    if(SomeEvent != null) { 
      arg.eventnum = count++; 
      Console.WriteLine("Event fired");
      SomeEvent(this, arg); 
    } 
  } 
} 
 
class X { 
  public void handler(object source, MyEventArgs arg) { 
    Console.WriteLine("Event " + arg.eventnum + " received by an X object."); 
    Console.WriteLine("Source is " + source); 
    Console.WriteLine(); 
  } 
} 
 
class Y {  
  public void handler(object source, MyEventArgs arg) { 
    Console.WriteLine("Event " + arg.eventnum + " received by a Y object."); 
    Console.WriteLine("Source is " + source); 
    Console.WriteLine(); 
  } 
} 
 
class MainClass { 
  public static void Main() {  
    X ob1 = new X(); 
    Y ob2 = new Y(); 
    MyEvent evt = new MyEvent(); 
 
    // Add handler() to the event list. 
    evt.SomeEvent += ob1.handler; 
    evt.SomeEvent += ob2.handler; 
 
    // Fire the event. 
    evt.OnSomeEvent(); 
    evt.OnSomeEvent(); 
  } 
}
Event fired
Event 0 received by an X object.
Source is MyEvent

Event 0 received by a Y object.
Source is MyEvent

Event fired
Event 1 received by an X object.
Source is MyEvent

Event 1 received by a Y object.
Source is MyEvent








23.64.event
23.64.1.Events
23.64.2.Using Event Accessors
23.64.3.Event and event handler
23.64.4.Use delegate to handle events
23.64.5.Fire event in property setter
23.64.6.Events: add and remove functions for a private delegate event
23.64.7.Events: add and remove functions
23.64.8.Events add and remove with synchronized block
23.64.9.Events: Custom Add and Remove with Global delegate cache.
23.64.10.A .NET-compatible event
23.64.11.Use the built-in EventHandler delegate
23.64.12.Use an anonymous method as an event handler
23.64.13.Ignored Parameters Anonymous Methods for Button click, kepressed and mouse clicked action
23.64.14.Events and form controls