Click here to Skip to main content
Licence 
First Posted 5 Sep 2005
Views 190,449
Bookmarked 86 times

The Simplest C# Events Example Imaginable

By | 5 Sep 2005 | Article
A simple metronome example where a class creates events and another receives them.

Introduction

Most examples of events and delegates in C# are more complicated and intimidating than a person new to both C# and OOP would like (VBA made it just too easy on us). While I will not explain the code, it is simple enough that what code to replace in a copy-paste is clear. I have created what I think may be one of the simplest examples of Event Handling in C#. A Metronome class creates events at a tick of 3 seconds, and a Listener class hears the metronome ticks and prints "HEARD IT" to the console every time it receives an event. This should give the novice programmer a clear idea what is necessary to generate and pass events. Plop the following code right into a class file in a blank C# project.

using System;
namespace wildert
{
    public class Metronome
    {
        public event TickHandler Tick;
        public EventArgs e = null;
        public delegate void TickHandler(Metronome m, EventArgs e);
        public void Start()
        {
            while (true)
            {
                System.Threading.Thread.Sleep(3000);
                if (Tick != null)
                {
                    Tick(this, e);
                }
            }
        }
    }
        public class Listener
        {
            public void Subscribe(Metronome m)
            {
                m.Tick += new Metronome.TickHandler(HeardIt);
            }
            private void HeardIt(Metronome m, EventArgs e)
            {
                System.Console.WriteLine("HEARD IT");
            }

        }
    class Test
    {
        static void Main()
        {
            Metronome m = new Metronome();
            Listener l = new Listener();
            l.Subscribe(m);
            m.Start();
        }
    }
}

A slightly more complicated example is if the event has information passed with it, such as mouse coordinates for a mouse event or which key is pressed for a keypress event. To do this you need to create an appropriate class derived from the EventArgs class and then set an instance of it before raising the event. See below:

using System;
namespace wildert
{
    
    public class TimeOfTick : EventArgs
    {
        private DateTime TimeNow;
        public DateTime Time
        {
            set
            {
                TimeNow = value;
            }
            get
            {
                return this.TimeNow;
            }
        }
    }
    public class Metronome
    {
        public event TickHandler Tick;
        public delegate void TickHandler(Metronome m, TimeOfTick e);
        public void Start()
        {
            while (true)
            {
                System.Threading.Thread.Sleep(3000);
                if (Tick != null)
                {
                    TimeOfTick TOT = new TimeOfTick();
                    TOT.Time = DateTime.Now;
                    Tick(this, TOT);
                }
            }
        }
    }
        public class Listener
        {
            public void Subscribe(Metronome m)
            {
                m.Tick += new Metronome.TickHandler(HeardIt);
            }
            private void HeardIt(Metronome m, TimeOfTick e)
            {
                System.Console.WriteLine("HEARD IT AT {0}",e.Time);
            }

        }
    class Test
    {
        static void Main()
        {
            Metronome m = new Metronome();
            Listener l = new Listener();
            l.Subscribe(m);
            m.Start();
        }
    }
}

When you add a button to a form in C# and double click on the button in the form designer, you are taken to a method equivalent to "Heardit", but it will be appropriately named something like Button1_Click. Button1 is set up with a standard event handler (System.EventHandler, which is discussed below in the comments) and its own events (Click, MouseMove, etc). If you dig into the Form1.Designer.cs code, you will find the last necessary bit of code.

this.button1.click += new System.EventHandler(this.button1_Click);

What the auto-designer code did for you was add a new class Button1 with Button events and uses System.EventHandler, and then had Form1 subscribe to its events and create a Button1_Click method in Form1. Awful English, I'm an engineer.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Todd Wilder

Web Developer

United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Question~6.5 years on and it's still helping people PinmemberBit55511:51 29 May '12  
Questionvery good article Pinmembermarek kaszycki8:57 21 Feb '12  
QuestionDelegates and Events PinmemberMember 861820620:04 7 Feb '12  
GeneralMy vote of 5 PinmemberGeorge Dawes22:15 16 Jan '12  
Rantsuggestion for easier reading Pinmembertaleofsixstrings6:47 18 May '11  
GeneralGreat Article Buddy....... PinmemberPratapDessai19:33 17 Feb '10  
GeneralRe: Great Article Buddy....... PinmemberMatic Marko21:22 6 Apr '10  
QuestionIs there code for a complete project? PinmemberJohn Chaffins10:32 16 Dec '09  
AnswerRe: Is there code for a complete project? PinmemberTodd Wilder11:07 16 Dec '09  
GeneralRe: Is there code for a complete project? PinmemberJohn Chaffins10:42 22 Dec '09  
GeneralPublish/Subscribe across user controls PinmemberKjartan937:38 3 Sep '09  
GeneralRe: Publish/Subscribe across user controls PinmemberTodd Wilder8:45 3 Sep '09  
QuestionWhat is the reason to check if the event is null? PinmemberMaxi Ng @ TW21:25 21 Jul '09  
AnswerRe: What is the reason to check if the event is null? PinmemberTodd Wilder12:38 22 Jul '09  
GeneralThanks! PinmemberGordopolis5:58 3 Sep '07  
GeneralAn excellent understandable article! Pinmemberthunderbirdje12:39 23 Aug '06  
You saved me 2 days of searching! Smile | :)
 
Finally after reading your article, my events work! Now I can fall asleep, at last Smile | :) )
 
Thanks for the article
GeneralPerfect Pinmembersnorkie10:33 9 Jun '06  
QuestionSimplified? PinmemberPeter Ritchie3:12 13 Sep '05  
GeneralSimplified Even Further... PinsussTimpie12:30 9 Sep '05  
GeneralMore so... PinmemberPinhead_Me7:07 7 Aug '06  
GeneralRe: More so... PinmemberTodd Wilder12:22 7 Aug '06  
GeneralGood job - very simple PinmemberSusan Hernandez6:10 7 Sep '05  
GeneralThanks! Pinmemberverger18:29 6 Sep '05  
GeneralDetail of System.Eventhandler Pinsusswildert9:17 6 Sep '05  
GeneralRe: Detail of System.Eventhandler Pinmembergleizerowicz9:50 9 Sep '05  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120529.1 | Last Updated 5 Sep 2005
Article Copyright 2005 by Todd Wilder
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid