How do I delay code execution in Visual Basic (VB6)?
Question
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'?
Solution
VB.Net: I would use a WaitOne event handle.
VB 6.0: I've seen a DoEvents Loop.
Do
If isSomeCheckCondition() Then Exit Do
DoEvents
Loop
Finally, You could just sleep:
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sleep 10000
OTHER TIPS
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).
Break your code up into 2 processes. Run the first, then run your "long running process", then run the second process.
Run your long-running process in the middle of your current process and wait for it to complete.
I wish you could just add the .net framework system.dll or whatever to your project references so that you could just do this:
Dim ALongTime As Integer = 2000
System.Threading.Thread.Sleep(ALongTime)
...every time. I have VB6, and VB.net 2008 on my machine, and its always difficult for me to switch between the very different IDE's.
System.Threading.Thread.Sleep(500)