How to delay code execution in Visual Basic (VB6)

processvb6

I have a long running process in VB6 that I want to finish before executing the next line of code. How can I do that? Built-in function? Can I control how long to wait?

Trivial example:

Call ExternalLongRunningProcess
Call DoOtherStuff

How do I delay 'DoOtherStuff'?

Best Answer

While Nescio's answer (DoEvents) will work, it will cause your application to use 100% of one CPU. Sleep will make the UI unresponsive. What you need is a combination of the two, and the magic combination that seems to work best is:

Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

While IsStillWaitingForSomething()
    DoEvents
    DoEvents
    Sleep(55)
Wend

Why two DoEvents, and one sleep for 55 milliseconds? The sleep of 55 milliseconds is the smallest slice that VB6 can handle, and using two DoEvents is sometimes required in instances when super-responsiveness is needed (not by the API, but if you application is responding to outside events, SendMessage, Interupts, etc).