29 January 2014

C# Timer

Windows Forms have a Timer control that can be used at design time as well as at run-time. In this article, I will discuss how to use a Timer control in a Windows Forms application at design-time as well as at run-time. 
A Timer control raises an event at a given interval of time without using a secondary thread. If you need to execute some code after certain interval of time continuously, you can use a timer control.
Timer Class Properties
Enabled property of timer represents if the timer is running. We can set this property to true to start a timer and false to stop a timer.
Interval property represents time on in milliseconds, before the Tick event is raised relative to the last occurrence of the Tick event. One second equals to 1000 milliseconds. So if you want a timer event to be fired every 5 seconds, you need to set Interval property to 5000.
Timer t = new Timer();
t.Interval = 2000;
timer1.Enabled = true;

Creating a Timer
A Timer control does not have a visual representation and works as a component in the background.
Design-time
You can create a timer at design-time by dragging and dropping a Timer component from Toolbox to a Form. After that, you can use F4 or right click Properties menu to set a Timer properties as shown in Figure 1. As you can see in Figure 1, the Enabled property is false and Interval is set to 1000 milliseconds (1 second).
TimerImg1.jpg
Figure 1
First thing you want to do is, change Enabled to true so the timer will start when your application starts.
Now next step is to add an event handler. If you go to the Events window by clicking little lightning icon, you will see only one Tick event as you can see from Figure 2. Double click on it will add the Tick event handler.
TimerImg2.jpg
Figure 2
The Tick event handler looks like following.
private void timer1_Tick(object sender, EventArgs e)
{
}

Now whatever code you write on this event handler, it will be executed every 1 second. For example, if you have a ListBox control on a Form and you want to add some items to it, the following code will do so.
private void timer1_Tick(object sender, EventArgs e)
{
    listBox1.Items.Add(DateTime.Now.ToLongTimeString() + "," + DateTime.Now.ToLongDateString());
}

Run-time
Timer class represents a Timer control and used to create a Timer at run-time. The following code snippet creates a Timer at run-time, sets its property and event handler.
Timer t = new Timer();
t.Interval = 2000;
timer1.Enabled = true;
timer1.Tick += new System.EventHandler(OnTimerEvent);

The event handler code looks like following.
private void OnTimerEvent(object sender, EventArgs e)
{
    listBox1.Items.Add(DateTime.Now.ToLongTimeString() + "," + DateTime.Now.ToLongDateString());
}

No comments:

Post a Comment