VB6 Timer Function
Microsoft’s Visual Basic 6 programming language has a comprehensive set of programmable software objects called controls, including a timer that allows programmers to create real-time applications with precise delays. Using the timer, a program “sleeps” for a predetermined period; when the interval elapses, Visual Basic interrupts what the computer is doing and carries out a task.
-
Description
-
As with other VB6 controls, the timer is an object in the Toolbox, appearing as a stopwatch icon. It has a time interval you set as you create the application or during program execution. When the timer counts down to zero, it triggers a specially assigned event subroutine into which you insert your own Visual Basic statements.
It becomes a part of your application when you drag the icon into the Form window. Though you see the time control when you create the program, it does not appear in any form window. Your application can have several timer controls, each set to different intervals and performing separate tasks.
Properties
-
The timer control has relatively few properties, the most significant being Interval, Enabled and Index. The Interval property holds an integer between zero and 65,535, which is the time delay in milliseconds. The Enabled property has values of True and False; if the program sets the value to False, the timer becomes inactive. Visual Basic assigns an integer to the Index property corresponding with a timer’s number in a control array, allowing you to identify different timers by specifying an index number in your program.
-
Event
-
The VB6 timer has a single event called Timer. When you drag the timer into your application’s form window and name the control, Visual Basic automatically creates a subroutine, “Private Sub objectname_Timer()” where objectname is the name you give to the control. When you run the application, and if the timer is enabled, the timer counts down the milliseconds you specified in the Interval property. When the interval times out, Visual Basic executes the code you have programmed in the Event subroutine.
DoEvents
-
For the timer to work, your Visual Basic program must not be executing code that does not release control back to Visual Basic and Windows. A prolonged calculation, for example, ties up the computer’s CPU and prevents any interruptions. If you use the VB6 DoEvents statement in your code, your program momentarily suspends itself, allowing Windows to service other programs. When the interval elapses, DoEvents permits the timer to interrupt what the program was doing and execute the code in the Timer event. DoEvents is therefore essential for the proper functioning of a program using the timer.
-
References
- Photo Credit Comstock/Comstock/Getty Images