Click here to Skip to main content
Click here to Skip to main content

The Simplest C# Events Example Imaginable

By , 5 Sep 2005
 

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
No Biography provided

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

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberHeaven202018 Mar '13 - 11:00 
GeneralMy vote of 4memberdhiraj226 Feb '13 - 18:26 
GeneralMy vote of 5memberMinghang21 Feb '13 - 20:31 
QuestionBest example on WebmemberBit_Flipper10 Jan '13 - 1:59 
GeneralMy vote of 5memberFranckyVercruysse2 Dec '12 - 8:12 
GeneralExcellentmemberMember 82577408 Nov '12 - 10:56 
QuestionVery Helpful!memberbentvisi0n26 Oct '12 - 10:56 
GeneralMy vote of 5memberSunny112224 Oct '12 - 22:12 
QuestionWhy event and Eventargs? [modified]memberhelpulearn.net28 Sep '12 - 17:01 
SuggestionGood, but still a bit complicated for beginner...memberMember 471378521 Sep '12 - 23:38 
GeneralMy vote of 5memberkarthikin6 Aug '12 - 0:25 
SuggestionSugestionmemberTheJediMaster4 Aug '12 - 9:07 
QuestionI am getting error in below codemembermahesh.b.p.c25 Jul '12 - 19:15 
AnswerRe: I am getting error in below codememberTodd Wilder25 Jul '12 - 19:36 
Questionthanksmemberafueo25 Jun '12 - 1:40 
Question~6.5 years on and it's still helping peoplememberBit55529 May '12 - 11:51 
AnswerRe: ~6.5 years on and it's still helping peoplememberAleholder28 Sep '12 - 9:50 
Questionvery good articlemembermarek kaszycki21 Feb '12 - 8:57 
QuestionDelegates and EventsmemberMember 86182067 Feb '12 - 20:04 
GeneralMy vote of 5memberGeorge Dawes16 Jan '12 - 22:15 
Rantsuggestion for easier readingmembertaleofsixstrings18 May '11 - 6:47 
GeneralGreat Article Buddy.......memberPratapDessai17 Feb '10 - 19:33 
GeneralRe: Great Article Buddy.......memberMatic Marko6 Apr '10 - 21:22 
QuestionIs there code for a complete project?memberJohn Chaffins16 Dec '09 - 10:32 
AnswerRe: Is there code for a complete project?memberTodd Wilder16 Dec '09 - 11:07 

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

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