How to wait for a shell process to finish before executing further code in VB6

前端 未结 7 873

I have a small VB6 app in which I use the Shell command to execute a program. I am storing the output of the program in a file. I am then reading this file and

7条回答
  •  萌比男神i
    2020-11-29 10:09

    There is no need to resort to the extra effort of calling CreateProcess(), etc. This more or less duplicates the old Randy Birch code though it wasn't based on his example. There are only so many ways to skin a cat.

    Here we have a prepackaged Function for handy use, which also returns the exit code. Drop it into a static (.BAS) module or include it inline in a Form or Class.

    Option Explicit
    
    Private Const INFINITE = &HFFFFFFFF&
    Private Const SYNCHRONIZE = &H100000
    Private Const PROCESS_QUERY_INFORMATION = &H400&
    
    Private Declare Function CloseHandle Lib "kernel32" ( _
        ByVal hObject As Long) As Long
    
    Private Declare Function GetExitCodeProcess Lib "kernel32" ( _
        ByVal hProcess As Long, _
        lpExitCode As Long) As Long
    
    Private Declare Function OpenProcess Lib "kernel32" ( _
        ByVal dwDesiredAccess As Long, _
        ByVal bInheritHandle As Long, _
        ByVal dwProcessId As Long) As Long
    
    Private Declare Function WaitForSingleObject Lib "kernel32" ( _
        ByVal hHandle As Long, _
        ByVal dwMilliseconds As Long) As Long
    
    Public Function ShellSync( _
        ByVal PathName As String, _
        ByVal WindowStyle As VbAppWinStyle) As Long
        'Shell and wait.  Return exit code result, raise an
        'exception on any error.
        Dim lngPid As Long
        Dim lngHandle As Long
        Dim lngExitCode As Long
    
        lngPid = Shell(PathName, WindowStyle)
        If lngPid <> 0 Then
            lngHandle = OpenProcess(SYNCHRONIZE _
                                 Or PROCESS_QUERY_INFORMATION, 0, lngPid)
            If lngHandle <> 0 Then
                WaitForSingleObject lngHandle, INFINITE
                If GetExitCodeProcess(lngHandle, lngExitCode) <> 0 Then
                    ShellSync = lngExitCode
                    CloseHandle lngHandle
                Else
                    CloseHandle lngHandle
                    Err.Raise &H8004AA00, "ShellSync", _
                              "Failed to retrieve exit code, error " _
                            & CStr(Err.LastDllError)
                End If
            Else
                Err.Raise &H8004AA01, "ShellSync", _
                          "Failed to open child process"
            End If
        Else
            Err.Raise &H8004AA02, "ShellSync", _
                      "Failed to Shell child process"
        End If
    End Function
    

提交回复
热议问题