Click here to Skip to main content
15,885,895 members
Articles / Programming Languages / C#
Article

The Simplest C# Events Example Imaginable

Rate me:
Please Sign up or sign in to vote.
4.11/5 (116 votes)
5 Sep 20052 min read 827.6K   143   62
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.

C#
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:

C#
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


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
d.albocha15-Aug-17 4:24
d.albocha15-Aug-17 4:24 
PraiseSomehow helpful Pin
Ammar Shaukat6-Apr-17 21:49
professionalAmmar Shaukat6-Apr-17 21:49 
Questiondifference between event and event handler? Pin
Member 117989123-Apr-17 2:57
Member 117989123-Apr-17 2:57 
Praisevery helpful, finally, thanks ! Pin
e_monteiro12-Jan-17 16:46
e_monteiro12-Jan-17 16:46 
QuestionGreat article - very helpful Pin
Daniel Miller18-Nov-15 6:33
professionalDaniel Miller18-Nov-15 6:33 
Questionplease could you explain how to use this alongside other code example Pin
archaeous2-Jul-15 0:18
archaeous2-Jul-15 0:18 
QuestionThanks so much! Pin
GIANGPZO13-Apr-15 17:10
professionalGIANGPZO13-Apr-15 17:10 
QuestionGreat Help Pin
Fredric Jerin12-Feb-15 18:37
Fredric Jerin12-Feb-15 18:37 
GeneralMy vote of 5 Pin
Ross Harrison113-Nov-14 7:22
Ross Harrison113-Nov-14 7:22 
GeneralMy vote of 1 Pin
maurices500011-Nov-14 9:49
maurices500011-Nov-14 9:49 
QuestionFinnally!! Pin
Pedro_RC_A3-Sep-14 14:39
Pedro_RC_A3-Sep-14 14:39 
QuestionNot explained simple Pin
Raja Chandrasekaran5-Jun-14 16:32
Raja Chandrasekaran5-Jun-14 16:32 
GeneralMy vote of 1 Pin
Mikant11-Apr-14 14:57
Mikant11-Apr-14 14:57 
Questionso nice Pin
Member 1058756019-Feb-14 18:19
Member 1058756019-Feb-14 18:19 
AnswerRe: so nice Pin
Fredric Jerin12-Feb-15 19:16
Fredric Jerin12-Feb-15 19:16 
GeneralMy Vote of 5 Pin
jardousman29-Dec-13 1:24
jardousman29-Dec-13 1:24 
QuestionAwesome Pin
tm7017014-Dec-13 8:01
tm7017014-Dec-13 8:01 
GeneralNote quite as simple as it could be Pin
Timok1A5-Aug-13 23:09
Timok1A5-Aug-13 23:09 
SuggestionRe: Note quite as simple as it could be Pin
WiiMaxx12-Dec-13 23:40
WiiMaxx12-Dec-13 23:40 
GeneralMy vote of 5 Pin
dano2k310-Jun-13 15:05
dano2k310-Jun-13 15:05 
GeneralMy vote of 5 Pin
Global Analyser18-Mar-13 11:00
Global Analyser18-Mar-13 11:00 
good idia
GeneralMy vote of 4 Pin
dhiraj226-Feb-13 18:26
dhiraj226-Feb-13 18:26 
GeneralMy vote of 5 Pin
Minghang21-Feb-13 20:31
Minghang21-Feb-13 20:31 
QuestionBest example on Web Pin
Bit_flipper10-Jan-13 1:59
Bit_flipper10-Jan-13 1:59 
GeneralMy vote of 5 Pin
FranckyVercruysse2-Dec-12 8:12
FranckyVercruysse2-Dec-12 8:12 

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

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