You are on page 1of 11

Visual Programming

Timer
LAB 11

Muhammad kamran
Email: kamran_comsian@ymail.com
Timer Control
• Windows Forms have a Timer control that can be
used 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.

2
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;
3
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).

4
Creating a Timer

5
Figure 1
Creating a Timer
• 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.
6
Creating a Timer

7
Creating a Timer

• The Tick event handler looks like following.

• private void timer1_Tick(object sender,


EventArgs e)

• {

• }
8
Creating a Timer
• 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());

• }

• 9
10
Questions?

You might also like