Visual Basic Concepts
When a timer control's interval elapses, Visual Basic generates the Timer event. Typically, you respond to this event by checking some general condition, such as the system clock.
A digital clock is a very simple but very useful application involving a timer control. Once you understand how the application works, you can enhance it to work as an alarm clock, stopwatch, or other timing device.
The Digital Clock application includes a timer and a label with a border. At design time, the application looks like Figure 7.47.
Figure 7.47 The Digital Clock application
At run time, the timer is invisible. The following table lists the property settings for the Digital Clock application.
Control | Property | Setting |
Label1 | BorderStyle | Fixed Single |
Timer1 | Interval | 500 (half a second) |
Timer1 | Enabled | True |
The only procedure in this application is an event procedure for the timer:
Private Sub Timer1_Timer ()
If lblTime.Caption <> CStr(Time) Then
lblTime.Caption = Time
End If
End Sub
The procedure displays the system time by calling the intrinsic Time function. This function returns a Variant containing the current time as a date/time value (VarType 7). When you assign it to a string variable or property, such as the Caption property in this case, Visual Basic converts it to a string using the time format specified in the Control Panel. If you want to display it using a different format, you can use the Format function.
For More Information See "Format Property."
The Interval property for the timer is set to 500, following the rule of setting the Interval to half of the shortest period you want to distinguish (one second in this case). This may cause the timer code to update the label with the same time twice in one second. This is wasteful and can cause some visible flicker, so the code tests to see if the time is different from what is displayed in the label before it changes the caption.
You can customize the look of the Digital Clock without having to write any additional statements. For example, you might want to select a different font for the label or change the BorderStyle property of the form.