DoEvents Function, DoEvents Statement

Example7X8XR8>Low

Causes Visual Basic to yield execution so that Microsoft Windows can process events.

Function Syntax

DoEvents( )

Statement Syntax

DoEvents

Remarks

The DoEvents function returns the number of visible forms.

DoEvents passes control to the Windows environment.  Control is not returned until the Windows environment has finished processing the events in its queue and all keys in the SendKeys queue have been sent.

Use DoEvents to interrupt processing so the Windows environment can respond normally to other events, such as keyboard input and mouse clicks.  If parts of your code take up too much processor time, use DoEvents to relinquish control to the Windows environment.

 

Caution      Make sure the procedure that has given up control with DoEvents is not executed again by a different part of your program before the first DoEvents call returns; this could cause unpredictable results.  In addition, do not use DoEvents if other applications could possibly interact with your procedure in unforeseen ways during the time you have yielded control.

 


DoEvents Statement Example

In this example, DoEvents yields to the Windows environment only in the second loop, allowing keystrokes every 1000 loops.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

 

Sub Form_Click ()

   Dim I, Msg, N                         ' Declare variables.

   MsgBox "Choose OK, then try pressing a key."

   For I = 1 To 15000                    ' Start first loop.

      N = Int(5000 * Rnd + 1)            ' Generate random number.

   Next I                                ' Increment loop counter.

   Msg = "Note that any keys you pressed weren't processed"

   Msg = Msg & " until the 1st loop was finished. Now choose OK"

   Msg = Msg & " and try again."

   MsgBox Msg                            ' Display message.

   For I = 1 To 15000                    ' Start second loop.

      N = Int(5000 * Rnd + 1)            ' Generate random number.

      If I Mod 1000 = 0 Then DoEvents    ' Yield to other events.

   Next I                                ' Increment loop counter.

   Msg = "During the second loop, your keystrokes were processed"

   Msg = Msg & " each time the count was evenly divisible by 1000."

   Msg = Msg & " improving the response but degrading the performance."

   MsgBox Msg                            ' Display message.

End Sub