Visual Basic for Financial Professionals
   Home      API Example1
Sometimes you might need to execute another program, a script, a batch file or in some other way pass the control to another process and then want to resume after this process is finished.
The code below uses two Windows API functions - OpenProcess and GetExitCodeProcess and the Shell function to achieve this. Via the Shell function the control is passed to an executable file called "c:myProgram.exe". The OpenProcess function returns the hProc id which is passed on to the GetExitCodeProcess inside the Loop which is exited once the lExitCode becomes different than the &H103 or in other words the "c:myProgram.exe" is no longer active.

It will be prudent of course to ensure there is an exit from the loop in case the executable hangs for a long time.

Private Declare Function OpenProcess Lib "kernel32" _
    (ByVal dwDesirecAccess As Long, _
     ByVal bInheritHandle As Long, _
     ByVal dwProcessId As Long) As Long
Private Declare Function GetExitCodeProcess Lib "kernel32" _
    (ByVal hProcess As Long, _
     lpExitCode As Long) As Long
Const AccessType = &H400
Const StillActive = &H103
Sub RunMyProgram()
    Dim TaskId As Long, hProc As Long, lExitCode As Long
    TaskId = Shell("c:myProgram.exe", vbHide)
    hProc = OpenProcess(AccessType, False, TaskId)
        GetExitCodeProcess hProc, lExitCode
    Loop While lExitCode = StillActive
    'Continue code below
End Sub