This second version attempts to
fix two problems in the first version. When you click on a button to start the loop
running, you now get feedback that something is happening. This visual feedback is in
the form of "dots" printed on the form itself:
For llCounter1 = 1 To 200
llAccum = 0
'Not in version 1
'Not in version 1
If llCounter1 Mod 10 = 0 Then Print ".";
For llCounter2 = 1 To 32000
llAccum = llAccum + 1
If you click on the End button
to stop the program, it is handled immediately. This is accomplished via the DoEvents
statement in the outer loop.
The purpose of DoEvents is to allow Windows to handle any user interface
events that are pending. In version 1 (without the DoEvents statement) nothing happens
when you clicked on the End button. In version 2, when you click the End button, the code
for its click event is executed the next time the outer loop executes, or almost
immediately. Then the program stops executing:
Private Sub cmdStop_Click()
Private Sub Form_Unload(Cancel As Integer)
|One thing to notice is that the program slows to a crawl if you place the
DoEvents statement in the second loop, which executes 32,000 times. You should write
your code carefully to not over use the DoEvents statement!
|If you click the buttons other than the End
button several times, you'll see that each click is handled immediately (more or less). If
you look carefully at the results printed on the form, you may be able to see that they
are not correct.
What happens is that each time you click on a button, the Click event
is stored by Windows. When a DoEvents statement is executed, Windows processes all user
interface events that are pending. DoEvents means "do user interface events".
The code that is currently executing is interrupted while the code in the Click event
of the pressed button is running. If you click the Variant button three times, the same
Click event code will run each time. However, when the last Click event is finished, the
program continues running from where it was interrupted. This seems like Magic!
|Solution A to
|Assume that you don't want executing code to be interrupted this way. Then
you should disable ALL command buttons at the beginning of the Click event code for each
This is done by setting the Enabled property to False. Then it would be
impossible to interrupt the code by pressing any command button. Of course, eventually
you'll need to re-enable the command buttons in code by setting the Enabled property to
This solution used for Version 3A of the program.
|Solution B to
|Assume that you want to allow the executing code to be interrupted.
Additional code needs to be written to clean up the display of the information on the
form. Even more code would need to be written to make the timing results show correct
This solution was used for Version 3B of the program.