Understanding Timer Control

A Timer control is invisible at run time, and its purpose is to send a periodic pulse to the current application. You can trap this pulse by writing code in the Timer’s Timer event procedure and take advantage of it to execute a task in the background or to monitor a user’s actions. This control exposes only two meaningful properties: Interval and Enabled. Interval stands for the number of milliseconds between subsequent pulses (Timer events), while Enabled lets you activate or deactivate events.

When you place the Timer control on a form, its Interval is 0, which means no events. Therefore, remember to set this property to a suitable value in the Properties window or in the Form_Load event procedure:

Private Sub Form_Load()Timer1.Interval = 500 ‘ Fire two Timer events per second.

End Sub

Some Points to note:

  • You must be careful not to write a lot of code in the Timer event procedure because this code will be executed at every pulse and therefore can easily degrade your application’s performance.
  • Just as important, never execute a DoEvents statement inside a Timer event procedure because you might cause the procedure to be reentered, especially if the Interval property is set to a small value and there’s a lot of code inside the procedure.
  • Timer controls are often useful for updating status information on a regular basis. For example, you might want to display on a status bar a short description of the control that currently has the input focus. You can achieve that by writing some code in the GotFocus event for all the controls on the form, but when you have dozens of controls this will require a lot of code (and time). Instead, at design time load a short description for each control in its Tag property, and then place a Timer control on the form with an Interval setting of 500. This isn’t a time-critical task, so you can use an even larger value.
  • Finally add two lines of code to the control’s Timer event:
Private Sub Timer1_Timer()
On Error Resume Next
lblStatusBar.Caption = ActiveControl.Tag
End Sub

A Small Program demonstrating use of timer Control.

Timer controls let you write interesting programs with just a few lines of code. The typical (and abused) example is a digital clock.

Private Sub Timer1_Timer()
Dim strTime As String
strTime = Time$
If Mid$(lblClock.Caption, 3, 1) = “:” Then
Mid$(strTime, 3, 1)= ” ”
Mid$(strTime, 6, 1) = ” ”
End If
lblClock.Caption = strTime
End Sub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s