Generic events : Generic Event : GUI Windows Forms C# Examples


C# Examples » GUI Windows Forms » Generic Event »

 

Generic events









    
using  System;    
    
class  MyEventArgs  :  EventArgs  {    
    public  int  eventnum;    
}    
  
delegate  void  MyEventHandler<T,  V>(T  source,  V  args);  
    
class  MyEvent  {    
    static  int  count  =  0;    
    
    public  event  MyEventHandler<MyEvent,  MyEventArgs>  SomeEvent;    
    
    public  void  OnSomeEvent()  {    
        MyEventArgs  arg  =  new  MyEventArgs();    
    
        if(SomeEvent  !=  null)  {    
            arg.eventnum  =  count++;    
            SomeEvent(this,  arg);    
        }    
    }    
}    
    
class  KeyBorardEventHandler  {    
    public  void  handler<T,  V>(T  source,  V  arg)  where  V  :  MyEventArgs  {    
        Console.WriteLine("Event  "  +  arg.eventnum  +    
                                            "  received  by  an  KeyBorardEventHandler  object.");    
        Console.WriteLine("Source  is  "  +  source);    
        Console.WriteLine();    
    }    
}    
    
class  MouseEventHandler  {      
    public  void  handler<T,V>(T  source,  V  arg)  where  V  :  MyEventArgs  {    
        Console.WriteLine("Event  "  +  arg.eventnum  +    
                                            "  received  by  a  MouseEventHandler  object.");    
        Console.WriteLine("Source  is  "  +  source);    
        Console.WriteLine();    
    }    
}    
  
class  UseGenericEventDelegate  {    
    public  static  void  Main()  {      
        KeyBorardEventHandler  ob1  =  new  KeyBorardEventHandler();    
        MouseEventHandler  ob2  =  new  MouseEventHandler();    
        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();    
    }    
}
    
   
  
   



Output

Event 0 received by an KeyBorardEventHandler object.
Source is MyEvent

Event 0 received by a MouseEventHandler object.
Source is MyEvent

Event 1 received by an KeyBorardEventHandler object.
Source is MyEvent

Event 1 received by a MouseEventHandler object.
Source is MyEvent


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo GUI Windows Forms
» Generic Event