Adding a Timer control in Visual Basic

A Timer control in Visual Basic is used for setting the time interval to execute any event after that interval. This is very useful if we want to perform some operations after a certain time. Say you want to create a backup of your data processing in every hour. You can make a routine which will take the backup and call that routine on Timer's event and set timer interval for an hour.

The code snippet given below gives an example of a timer that prints off a line after every second into a list box.

In this example we need 4 command buttons with the following names/captions.

#1 Command Button:
Name: cmdStart
Caption: Start Timer

#2 Command Button:
Name: cmdStop
Caption: Stop Timer

#3 Command Button:
Name: cmdClear
Caption: Clear Text

#4 Command Button:
Name: cmdExit
Caption: Exit


1 ListBox
With:

Name:lstCount
Caption: (None)

1 Timer
With:

Name: tmrTimer
Caption: (None)


The Code is given below:


Add this code to General Declarations:
{CODE}
Dim Response As Integer
Dim mintCount As Integer


Then this:


Private Sub cmdClear_Click()
lstCount.Clear
End Sub

Private Sub cmdExit_Click()
Response = MsgBox("Exit Program?", vbInformation + vbYesNo, "Are you sure?")
If Response = vbYes Then
Unload Me
ElseIf Response = vbNo Then
Me.Refresh
End If
End Sub

Private Sub cmdStart_Click()
mintCount = 0
Cls
tmrTimer.Enabled = True
End Sub


Private Sub cmdStop_Click()
tmrTimer.Enabled = False
End Sub

Private Sub tmrTimer_Timer()
mintCount = mintCount + 1
lstCount.AddItem "Timer fired again. Count = " & mintCount
End Sub


Whenever you click the "Clear Text" button, the ListBox will be cleared of all text.

If you click the "Exit" button, it asks you if you REALLY want to exit. If YES then it will exit, if NO then it will just go back to the previous screen.

The timer will start everytime you click on "Start Timer" button.
The timer will stop when ever you click on "Stop Timer" Button

Finally the text "Timer fired again. Count = ?" is added into the ListBox every time.

Hope this is very useful to all members

Raghav


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: