If you are a new VB programmer and have begun to develop more sophisticated applications to do animations, heavy number crunching, etc., you may have noticed that sometimes those apps seem to take control of Windows while they run. For example, your mouse clicks and keystrokes may take a long time to register with your app and others. You may not even see your mouse moving with you fast enough.
The good news is that it's fairly easy to correct this problem.
While newer versions of Windows support "simultaneous" multitasking using "time slices" for each process, Windows is still a non-preemptive operating system at its core. "Preemptive multitasking" means that the operating system (OS) gives each running process a slice of time running on the CPU before it interrupts it to give CPU control to the next process. Each process need not care about the CPU needs of any other. "Nonpreemptive multitasking" means that the processes are expected to voluntarily yield control of the CPU to the OS so it can give control to the next running program.
Roughly speaking, if you're not somehow giving control of the CPU back to Windows, other apps can't use it.
Most simple VB programs get control when Windows triggers an event, like a button click or mouse movement. If your app responds to the event, it automatically gives control back to Windows when the responding event (e.g., Command1_Click() ) is done executing. But if it doesn't exit within a few seconds, you may start to notice your app is hogging resources.
Fortunately, VB comes with a built in routine to voluntarily give control of the CPU back to Windows for a while: DoEvents. Consider the following simple program:
Private GoForIt As Boolean
Private Sub Command1_Click()
If GoForIt Then 'Clicked to stop
GoForIt = False
Else 'Clicked to start
GoForIt = True
Do While GoForIt
Command1.Caption = Rnd
Private Sub Form_Unload(Cancel As Integer)
GoForIt = False 'Break out of the loop
Notice how DoEvents is used in Form_Unload() to let the loop initiated in Command1_Click(), if it's still running, finish and exit? That's right; one chunk of your own code can be running "in parallel" with another chunk in your program. You don't have to mess with multithreading or multiprocessing to have this happen. This is another benefit of using DoEvents liberally and carefully.
In summary, use DoEvents to break up algorithms that take a long time or loop continuously to give Windows a chance now and then to do other things with the CPU.