How to use timers

In this tutorial I'm going to explain how to use timers in your Visual Basic application. This tutorial is understandable if you know a little bit about Visual Basic.

-First we make the interface. Make three command-buttons on the left side of the form. Change the caption of command1 into 'Click here to enable timer1'. Change the caption of command2 into 'Click here to enable timer2' and change the last caption into 'Stop the timers'.

-Now make a big picturebox on the right side of the commandbuttons. Give it a height of 4500 and a width of 4000 twips. If the form is to small, make the form bigger. Make the backcolor black. Make another picturebox within the big picturebox with a height and width of 375. Change the backcolor into green and the name in picMoveIt.

-The last thing to do is to make 2 timers. One timer is for the movement of picMoveIt to the right and the other for the movement down. Change the interval of the timers into a number between 10 and 100. The lower the interval, the faster picMoveIt moves. Change the property enabled from True into False.

-The interface is ready. Now let's start coding the timers. Double click on timer1. Type or copy and paste the following lines:

If picMoveIt.Left < 3400 Then
picMoveIt.Left = picMoveIt.Left + 100
End If

This means that every 10 to 100 milliseconds (depends on the interval of timer1) this code is called. So every time the leftcoordinate of picMoveIt gets higher. In other words, the distance between the left side of picMoveIt and the leftside of Picture1 (the big picturebox) changes a few times per second. It looks like the picturebox moves. The if..then statement checks if picMoveIt is still in the boundaries of Picture1.

-Timer 2 is almost the same function, the only difference is that it makes picMoveIt move down. The code is:

If picMoveIt.Top < 3900 Then
picMoveIt.Top = picMoveIt.Top + 100
End If

-The command buttons will activate and deactivate the timers. The code for command button 1: Timer1.Enabled = True. The code for command button 2 is: Timer2.Enabled = True. The code for commandbutton 3: Timer1.Enabled = False
Timer2.Enabled = False
I think this last code isn't very hard to understand.

That was it. You can download this tutorial by clicking HERE. If you have any questions, e-mail me by clicking here.

<-- Back to tutorials