"steve marchant" <st**************@tiscali.co.uk> wrote in message
news:44**********@mk-nntp-2.news.uk.tiscali.com...
trying to learn VB6. Simple counting loop which counts to 8 in 1 sec
intervals, then starts from 1 again and repeats.
Have two Command buttons on the form. Cmd1 starts the counting, and I need to
know how to stop it with Cmd2.
Having posted Lesson 1: Control Your Loops, now here is
Lesson 2: Use a Timer Control Instead
To see why, you will need to bring up Task Manager, so you can monitor CPU
usage.
The first method, using DoEvents, will cause your program to hog the CPU, at
100% use.
For counting off seconds (an eternity to a computer), this is quite a waste.
Here is what the same program would look like using a timer control.
I have named the timer control TimerCtrl to help avoid confusion.
Note though that VB calls the timer tick event TimerCtrl_Timer().
Also note that the variables x and m have been moved out of procedures.
The big advantage here is that your program checks the time every 1/10 of a
second (interval = 100 msec), and then releases the CPU until the next timer
event fires. The CPU use will stay around 1% max. DoEvents is not needed,
because you are not hogging the CPU in the first place.
Private x As Single
Private m As Single
Private Sub Form_Load()
TimerCtrl.Interval = 100
TimerCtrl.Enabled = False
End Sub
Private Sub Command1_Click()
x = Timer()
m = 1
Cls
Print m
TimerCtrl.Enabled = True
End Sub
Private Sub Command2_Click()
TimerCtrl.Enabled = False
Print "stopped"
End Sub
Private Sub TimerCtrl_Timer()
If Timer() > x + 1 Then
m = m + 1
If m > 8 Then m = 1
Print m
x = Timer()
End If
End Sub