xbdev - software development
Wednesday February 1, 2023
home | about | contact | Donations



With C# and .Net...


Timer...tick tick tick...



Some times we need to have a way of being notified when a certain amount of time has passed.... seconds...minutes or even hours...  The simplest way of getting time feedback is by using the build in windows timer... which we'll see how to use now.





Now every 25milliseconds the counter increases...so if you watch the caption box at the top of the window you'll see our timer working.




The code is simple....but it still has a few things which make it tricky to understand, because we need a IContainer object to work with a Timer....so we have to initialize that first then setup our timer and where ready to go!  An int variable is incremented each time the timer variable is called so we can see our call back function working.  Its sweet and simple I always like to say.



Code: timer.cs

// timer.cs


// C:>csc /t:winexe timer.cs


// Well we want our program to be in a GUI window, so we need to inherit

// from Form, which is in the library 'System.Windows.Forms'.


class SimpleWindow : System.Windows.Forms.Form


      private System.Windows.Forms.Timer       Ticker;

      private System.ComponentModel.IContainer components;


      private int i;

      private void Ticker_Tick(object sender, System.EventArgs e)



            this.Text = "Tick: " + i;


      } // End of Ticker_Tick(..)   this.Text = title;


      // Window constructor



            i = 0;


            this.components = new System.ComponentModel.Container();

            this.Ticker = new System.Windows.Forms.Timer(this.components);


            this.Ticker.Interval = 25;

            this.Ticker.Tick += new System.EventHandler(this.Ticker_Tick);

            Ticker.Enabled = true;



      // Our program entry point.

      static void Main()


            System.Windows.Forms.Application.Run(new SimpleWindow());


}// End of SimpleWindow Class



You could maybe alter the code slightly so that every 25 milliseconds an object on the screen moves, giving a simple animation... possibly a ball bouncing around the screen.... or if you work from one of the earlier tutorials on moving a window - possibly have the window move around the screen...giving the foundation for a screenmate project.


So all you have to do to setup a timer is remember the following few lines of code:



// Start/Init Timer

            // --- Timer --- //

            this.Ticker = new System.Windows.Forms.Timer();

            this.Ticker.Interval = 25;

            this.Ticker.Tick += new System.EventHandler(this.OnTimer);

            Ticker.Enabled = true;

// Timer Function to be called

            private void Ticker_Tick(object sender, System.EventArgs e)






 Visitor: 9534626
{ }
Copyright (c) 2002-2020 xbdev.net - All rights reserved.
Designated articles, tutorials and software are the property of their respective owners.