How do I Execute a Program And Wait Until it is Done

You may have noticed that when many compression programs execute a file they wait until it is done to clean up the temporary files made. This can be done in both Windows 3.1x and, of course in Windows 32 bit. Here’s the code for Windows 16 bit:

uses
  Wintypes, WinProcs, Toolhelp, Classes, Forms;
  ...
function WinExecAndWait(sPath: string; wVisibility: Word): Word;
var
  iPathLen : Integer;
  hInstance: THandle;
begin
  { Inplace conversion of a string to a PChar }
  iPathLen := Length(sPath);
  Move(sPath[1], sPath[0], iPathLen);
  sPath[iPathLen] := #0;
  { Try to run the application }
  hInstance := WinExec(@sPath, wVisibility);
  if hInstance < 32 then { A value less than 32 indicates an Exec error }
    WinExecAndWait := hInstance
  else begin
    repeat
      Application.ProcessMessages;
    until Application.Terminated or (GetModuleUsage(hInstance) = 0);
    WinExecAndWait := 32;
  end;
end;

…and the code for Windows 32 bit. The following function starts an executable with a given command line. If the execution fails (non-0 return value
from executable), the return value is False, and (GetLastError - $2000) is the return value from the executable. If the execution is successful (return value 0 from the executable), the return value is True.


function ExecAndWait(sExe, sCommandLine: string): Boolean;
var
  dwExitCode: DWORD;
  tpiProcess: TProcessInformation;
  tsiStartup: TStartupInfo;
begin
  Result := False;

  FillChar(tsiStartup, SizeOf(TStartupInfo), 0);
  tsiStartup.cb := SizeOf(TStartupInfo);
  if CreateProcess(PChar(fsExe), PChar(sCommandLine), nil, nil, False, 0, nil, nil, tsiStartup, tpi) then begin
    if WAIT_OBJECT_0 = WaitForSingleObject(tpiProcess.hProcess, INFINITE) then begin
      if GetExitCodeProcess(tpiProcess.hProcess, dwExitCode) then begin
        if dwExitCode = 0 then begin
          Result := True;
        end else begin
          SetLastError(dwExitCode + $2000);
        end;
      end;
    end;
    dwExitCode := GetLastError;
    CloseHandle(tpiProcess.hProcess);
    CloseHandle(tpiProcess.hThread);
    SetLastError(dwExitCode);
  end;
end;

Tags: , , , , , , , , , , , ,

No Comments Yet

You can be the first to comment!

Leave a comment

OpenID Login

Standard Login