Examples: Yield function and statement

Yield control to allow the user to perform one or more calculations. When the user is done, continue with the script.

The DoCalc sub uses a Shell statement to start the Windows calculator. The Shell statement returns the calculator task ID (also known as the module handle). In a While loop, the sub calls the GetModuleUsage Windows 3.1 API function, which returns the module reference count (how many instances of the calculator are currently running). The Yield statement yields control to the calculator. When the user closes the calculator, GetModuleUsage returns a reference count of 0, the While loop ends, and the sub displays an appropriate message.

If you remove the While loop (try it), the message box appears as soon as the calculator begins running. In other words, the script continues to execute without yielding control to the calculator.

' Declare the Windows 3.1 API function at the module level.
Declare Function GetModuleUsage Lib "Kernel" _
   (ByVal taskID As Integer) As Integer
Sub DoCalc
   Dim taskID As Integer
   ' Start the Windows calculator, returning its task ID.
   taskID% = Shell("calc.exe", 1)
   ' As long as the module is still running, yield.
   Do While GetModuleUsage(taskID%) > 0
      Yield
   Loop
   ' When the user closes the calculator, continue.
   MessageBox "Calculations done"
End Sub
DoCalc                ' Call the DoCalc sub.