Generic Based Event Handling Demo for VS.Net 2005


/ Published in: C#
Save to your folder(s)

Annotated version of the Microsoft/GotDotNet demo from the MSDN Wiki.


Copy this code and paste it in your HTML
  1. //Define a custom EventArgs class to contain your data.
  2. public class MyEventArgs : EventArgs
  3. {
  4. public string info = "data";
  5. }
  6.  
  7. //Declare the event as visible to users of the class
  8.  
  9. public event EventHandler<MyEventArgs> MyEvent;
  10.  
  11.  
  12. //Send the event, note that this will throw a nullref if there are no subscribers
  13.  
  14. //Internal version prevents outsiders from needing to know about the contents of MyEventArgs
  15. protected virtual void InternalSendMyEvent(CustomEventArgs e)
  16. {
  17. if(MyEvent != null)
  18. {
  19. e.info = "Hello Events!";
  20. //This calls all registered subscribers with the following parameters.
  21. MyEvent(this, e);
  22. }
  23. }
  24.  
  25. //Public version to allow outsiders to trigger the event, not typical implementation.
  26. public void CreateEvent()
  27. {
  28. InternalSendMyEvent(new MyEventArgs());
  29. }
  30.  
  31.  
  32.  
  33. //Consumer
  34. //Register the Handler
  35.  
  36. eventRaiser.MyEvent += new EventHandler<CustomEventArgs>(HandleEvent);
  37.  
  38. //Define the Handler
  39. private void HandleEvent(object sender, MyEventArgs e)
  40. {
  41. MessageBox.Show("Event handled:" + e.info);
  42. }
  43.  
  44.  
  45. //Cause the Event
  46. eventRaiser.CreateEvent();

URL: http://msdnwiki.microsoft.com/en-us/mtpswiki/402101b6-555d-4cf7-b223-1d9fdfaaf1cd.aspx

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.