Using CreateProcess() to launch another application and wait until it's finished
   


This function is the same as WinExec32(), but it allows you to tell Delphi to wait until the launching application is done before continuing on to the next line of code. Again, the list of variables passed to Visibility is in Win32.hlp under 'ShowWindow()'.

Added
CloseHandle() calls to close the handles since they are no longer needed. Thanks to Kevin S. Gallagher for this addition.

{$DEFINE Delphi3Below}
{$IFDEF VER130} //Delphi 5
  {$UNDEF Delphi3Below}
{$ELSE}
  {$IFDEF VER120} //Delphi 4
    {$UNDEF Delphi3Below}
  {$ENDIF}
{$ENDIF}

{ WinExecAndWait32 ******************************************** }
{ 32 bit routine that will launch an app and wait for it to }
{ finish. Works on 32 bit & 16 bit exe's as well as .pifs }
{ ************************************************************* }
function WinExecAndWait32(FileName: string; Visibility: integer): integer;
{ returns -1 if the Exec failed, otherwise returns the process' }
{ exit code when the process terminates. }

var
  zAppName: array[0..512] of char;
  zCurDir : array[0..255] of char;
  WorkDir : string;
  StartupInfo: TStartupInfo;
  ProcessInfo: TProcessInformation;
  {$IFNDEF Delphi3Below}

  CardinalResult: cardinal;
  {$ENDIF}

begin
  FillChar(zAppName, Sizeof(zAppName), #0);
  FillChar(zCurDir, Sizeof(zCurDir), #0);
  StrPCopy(zAppName, FileName); 
  GetDir(0, WorkDir);
  StrPCopy(zCurDir, WorkDir);
  FillChar(StartupInfo, Sizeof(StartupInfo), #0);
  StartupInfo.cb := Sizeof(StartupInfo);
  StartupInfo.dwFlags := STARTF_USESHOWWINDOW;
  StartupInfo.wShowWindow := Visibility;
  if not CreateProcess(nil,
                       zAppName, { pointer to command line string }
                       nil{ pointer to process security attributes }
                       nil{ pointer to thread security attributes }

                       false, { handle inheritance flag }

                       CREATE_NEW_CONSOLE or { creation flags }

                       NORMAL_PRIORITY_CLASS,
                       nil{ pointer to new environment block }

                       nil{ pointer to current directory name }

                       StartupInfo, { pointer to STARTUPINFO }

                       ProcessInfo) then { pointer to PROCESS_INF }

    Result := -1
  else
    begin
      WaitforSingleObject(ProcessInfo.hProcess, INFINITE);
      {$IFNDEF Delphi3Below}

      GetExitCodeProcess(ProcessInfo.hProcess, CardinalResult);
      Result := CardinalResult;
      {$ELSE}

      GetExitCodeProcess(ProcessInfo.hProcess, Result);
      {$ENDIF}

      CloseHandle(ProcessInfo.hProcess);
      CloseHandle(ProcessInfo.hThread);
    end;
end;


Blue Orb Software

[email protected]