Thursday, November 11, 2010

Timer VB6.0

The Timer control allows you to perform a task at a specified interval or to wait for a specified length of time.

Timer Example 1

  • Start a new VB project and place two command buttons and a timer control on the form. Set the properties of the controls as follows:

Control Property Value
Command Button (Name) cmdStart
Caption Start Timer

Command Button (Name) cmdStop
Caption Stop Timer

Timer (Name) tmrTest
Enabled False
Interval 250

Your form should look something like this:


Consider the following facts about the Timer control:
Ø       It is not visible to the user at run-time
Ø       The actions that you want to happen at the specified interval are coded in the Timer's Timer event.
Ø       You specify the interval that you want actions to occur in the Timer control's Interval property. The value is specified in milliseconds (1000 milliseconds = 1 second). In the example, the value of 250 will cause the Timer event to fire every quarter of a second.
Ø       You turn the timer "on" or "off" by setting its Enabled property to True or False, respectively. The Enabled property is set to True by default.

  • Place the following declaration in the Form's General Declarations section:

Private mintCount As Integer

  • Code the Click event for the two command buttons and the Timer event for the timer control as follows:

Private Sub cmdStart_Click()

mintCount = 0
Cls
tmrTest.Enabled = True

End Sub

Private Sub cmdStop_Click()

tmrTest.Enabled = False

End Sub


Private Sub tmrTest_Timer()

mintCount = mintCount + 1
Print "Timer fired again. Count = " & mintCount
End Sub

  • Run the program. Click the "Start Timer" button. Messages will appear on the form every quarter of a second. They will stop when you click the "Stop Timer" button. A sample run might look like this:



Download the VB project code for the example above here.

Timer Example 2

The Timer control can be used to make an object on your screen appear to blink. This is done by toggling the Visible property of the object on and off at short intervals. The Visible property is available to nearly all controls – it is a Boolean property that determines whether or not the control is visible to the user at run time by setting its value to True or False (it will always be visible at design time). To build a simple demo, perform the following steps.

  • Start a new VB project.
  • Place a label on the form and name it lblProcessing. Set its Caption to Processing . . . Please Wait. Set it to a large font and set its Forecolor property to the color of your choice. Center it on your form.
  • Place a timer on the form and name it tmrBlink. Set its Interval property to 250.
  • In the tmrBlink_Timer event, place the following single line of code:

lblProcessing.Visible = Not lblProcessing.Visible

  • Run the project. The label will blink. After an appropriate period of observation, close the form.


No comments:

Post a Comment