Click here to Skip to main content
11,414,234 members (71,376 online)
Click here to Skip to main content

The Simplest C# Events Example Imaginable

, 5 Sep 2005
Rate this:
Please Sign up or sign in to vote.
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

Share

About the Author

Todd Wilder
Web Developer
United States United States
No Biography provided

Comments and Discussions

 
QuestionThanks so much! Pin
GIANGPZO, 13-Apr-15 18:10
professionalGIANGPZO13-Apr-15 18:10 
QuestionGreat Help Pin
Member 10986859, 12-Feb-15 19:37
memberMember 1098685912-Feb-15 19:37 
GeneralMy vote of 5 Pin
Ross Harrison1, 13-Nov-14 8:22
memberRoss Harrison113-Nov-14 8:22 
GeneralMy vote of 1 Pin
maurices5000, 11-Nov-14 10:49
membermaurices500011-Nov-14 10:49 
QuestionFinnally!! Pin
Member 10939870, 3-Sep-14 15:39
memberMember 109398703-Sep-14 15:39 
QuestionNot explained simple Pin
Raja Chandrasekaran, 5-Jun-14 17:32
memberRaja Chandrasekaran5-Jun-14 17:32 
GeneralMy vote of 1 Pin
Mikant, 11-Apr-14 15:57
memberMikant11-Apr-14 15:57 
Questionso nice Pin
Member 10587560, 19-Feb-14 19:19
memberMember 1058756019-Feb-14 19:19 
AnswerRe: so nice Pin
Member 10986859, 12-Feb-15 20:16
memberMember 1098685912-Feb-15 20:16 
GeneralMy Vote of 5 Pin
jardousman, 29-Dec-13 2:24
memberjardousman29-Dec-13 2:24 
QuestionAwesome Pin
tm701701, 4-Dec-13 9:01
membertm7017014-Dec-13 9:01 
GeneralNote quite as simple as it could be Pin
Timok1A, 6-Aug-13 0:09
memberTimok1A6-Aug-13 0:09 
SuggestionRe: Note quite as simple as it could be [modified] Pin
WiiMaxx, 13-Dec-13 0:40
memberWiiMaxx13-Dec-13 0:40 
GeneralMy vote of 5 Pin
dano2k3, 10-Jun-13 16:05
memberdano2k310-Jun-13 16:05 
GeneralMy vote of 5 Pin
Heaven2020, 18-Mar-13 12:00
memberHeaven202018-Mar-13 12:00 
GeneralMy vote of 4 Pin
dhiraj2, 26-Feb-13 19:26
memberdhiraj226-Feb-13 19:26 
GeneralMy vote of 5 Pin
Minghang, 21-Feb-13 21:31
memberMinghang21-Feb-13 21:31 
QuestionBest example on Web Pin
Bit_Flipper, 10-Jan-13 2:59
memberBit_Flipper10-Jan-13 2:59 
GeneralMy vote of 5 Pin
FranckyVercruysse, 2-Dec-12 9:12
memberFranckyVercruysse2-Dec-12 9:12 
GeneralExcellent Pin
Member 8257740, 8-Nov-12 11:56
memberMember 82577408-Nov-12 11:56 
QuestionVery Helpful! Pin
bentvisi0n, 26-Oct-12 11:56
memberbentvisi0n26-Oct-12 11:56 
GeneralMy vote of 5 Pin
Sunny1122, 24-Oct-12 23:12
memberSunny112224-Oct-12 23:12 
QuestionWhy event and Eventargs? [modified] Pin
helpulearn.net, 28-Sep-12 18:01
memberhelpulearn.net28-Sep-12 18:01 
SuggestionGood, but still a bit complicated for beginner... Pin
Member 4713785, 22-Sep-12 0:38
memberMember 471378522-Sep-12 0:38 
GeneralMy vote of 5 Pin
karthikin, 6-Aug-12 1:25
memberkarthikin6-Aug-12 1:25 
SuggestionSugestion Pin
TheJediMaster, 4-Aug-12 10:07
memberTheJediMaster4-Aug-12 10:07 
QuestionI am getting error in below code Pin
mahesh.b.p.c, 25-Jul-12 20:15
membermahesh.b.p.c25-Jul-12 20:15 
AnswerRe: I am getting error in below code Pin
Todd Wilder, 25-Jul-12 20:36
memberTodd Wilder25-Jul-12 20:36 
Questionthanks Pin
afueo, 25-Jun-12 2:40
memberafueo25-Jun-12 2:40 
Question~6.5 years on and it's still helping people Pin
Bit555, 29-May-12 12:51
memberBit55529-May-12 12:51 
AnswerRe: ~6.5 years on and it's still helping people Pin
Aleholder, 28-Sep-12 10:50
memberAleholder28-Sep-12 10:50 
Questionvery good article Pin
marek kaszycki, 21-Feb-12 9:57
membermarek kaszycki21-Feb-12 9:57 
QuestionDelegates and Events Pin
Member 8618206, 7-Feb-12 21:04
memberMember 86182067-Feb-12 21:04 
GeneralMy vote of 5 Pin
George Dawes, 16-Jan-12 23:15
memberGeorge Dawes16-Jan-12 23:15 
Rantsuggestion for easier reading Pin
taleofsixstrings, 18-May-11 7:47
membertaleofsixstrings18-May-11 7:47 
GeneralGreat Article Buddy....... Pin
PratapDessai, 17-Feb-10 20:33
memberPratapDessai17-Feb-10 20:33 
GeneralRe: Great Article Buddy....... Pin
Matic Marko, 6-Apr-10 22:22
memberMatic Marko6-Apr-10 22:22 
QuestionIs there code for a complete project? Pin
John Chaffins, 16-Dec-09 11:32
memberJohn Chaffins16-Dec-09 11:32 
AnswerRe: Is there code for a complete project? Pin
Todd Wilder, 16-Dec-09 12:07
memberTodd Wilder16-Dec-09 12:07 
GeneralRe: Is there code for a complete project? Pin
John Chaffins, 22-Dec-09 11:42
memberJohn Chaffins22-Dec-09 11:42 
GeneralPublish/Subscribe across user controls Pin
Kjartan93, 3-Sep-09 8:38
memberKjartan933-Sep-09 8:38 
GeneralRe: Publish/Subscribe across user controls Pin
Todd Wilder, 3-Sep-09 9:45
memberTodd Wilder3-Sep-09 9:45 
QuestionWhat is the reason to check if the event is null? Pin
Maxi Ng @ TW, 21-Jul-09 22:25
memberMaxi Ng @ TW21-Jul-09 22:25 
AnswerRe: What is the reason to check if the event is null? Pin
Todd Wilder, 22-Jul-09 13:38
memberTodd Wilder22-Jul-09 13:38 
GeneralThanks! Pin
Gordopolis, 3-Sep-07 6:58
memberGordopolis3-Sep-07 6:58 
GeneralAn excellent understandable article! Pin
thunderbirdje, 23-Aug-06 13:39
memberthunderbirdje23-Aug-06 13:39 
GeneralPerfect Pin
snorkie, 9-Jun-06 11:33
membersnorkie9-Jun-06 11:33 
QuestionSimplified? Pin
Peter Ritchie, 13-Sep-05 4:12
memberPeter Ritchie13-Sep-05 4:12 
GeneralSimplified Even Further... Pin
Timpie, 9-Sep-05 13:30
sussTimpie9-Sep-05 13:30 
GeneralMore so... Pin
Pinhead_Me, 7-Aug-06 8:07
memberPinhead_Me7-Aug-06 8:07 

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.

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