Waiting for an application to finish executing 

This code is extremely useful when you need to let a program complete doing whatever it does before your program can continue. An example is when you let WinZip create a ZIP file for you but you cannot continue until the ZIP has been created.

 

function WinExecAndWait32(Path: PChar; Visibility: Word): integer;
var Msg: TMsg;
    { Delphi 3:    lpExitCode: integer; }
    { Delphi 4 information courtesy of Joel Milne }
    { Delphi 4: }  lpExitCode: cardinal;
    StartupInfo: TStartupInfo;
    ProcessInfo: TProcessInformation;
begin
  FillChar(StartupInfo, SizeOf(TStartupInfo), 0);
  with StartupInfo do
  begin
    cb := SizeOf(TStartupInfo);
    dwFlags := STARTF_USESHOWWINDOW or STARTF_FORCEONFEEDBACK;
    wShowWindow := visibility; {you could pass sw_show or sw_hide as parameter}
  end;

  if CreateProcess(nil, path, nil, nil, False, NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo,
                   ProcessInfo) then
  begin
    repeat
      while PeekMessage(Msg, 0, 0, 0, pm_Remove) do
      begin
        if Msg.Message = wm_Quit then Halt(Msg.WParam);
        TranslateMessage(Msg);
        DispatchMessage(Msg);
      end;
      GetExitCodeProcess(ProcessInfo.hProcess,lpExitCode);
    until lpExitCode <> Still_Active;

    with ProcessInfo do {not sure this is necessary but seen in in some code elsewhere}
    begin
      CloseHandle(hThread);
      CloseHandle(hProcess);
    end;
    Result := 0; {success}
  end else Result := GetLastError;
end;
 

Return to the main page


This page was created by Ashley Godfrey, 1998.
Borland Delphi is a registered trademark of Inprise Corporation
Window's 95 and Internet Explorer are registered trademarks of Microsoft Corporation
All other products and logos are the property of theor respective owners
Inprise Corporation is in no way affiliated with Ashley Godfrey, this site or any of his software.