Mega Code Archive

 
Categories / Delphi / API
 

How to run another program and wait until its finished

function TForm1.RunProgramWait ( ProgramName, CommandLine : string; dwCreationFlags: dWord = 0; HowToShowWindow :dWord=SW_SHOWNORMAL) : integer; var StartupInfo : TStartupInfo; ProcessInfo : TProcessInformation; Code : Cardinal; begin FillChar(StartupInfo, sizeof(TStartupInfo),0) with StartupInfo do //recreates record for start begin cb := SizeOf( StartupInfo); dwFlags := STARTF_USESHOWWINDOW; wShowWindow := HowToShowWindow; end; Code := 0; Application.Hint := 'Starting ' + ProgramName + '...'; if CreateProcess(nil, PChar(ProgramName + ' ' + CommandLine), nil, nil, False, dwCreationFlags, nil, PChar(ExtractFilePath(ProgramName)), StartupInfo, ProcessInfo) then //starts the application begin caption := ProgramName + ' -Active'; //loop to check if application is terminated or not while GetExitCodeProcess(ProcessInfo.hProcess, Code) and (Code = STILL_ACTIVE) do begin Application.ProcessMessages; Sleep(1000); //to reduce CPU load the higher the better. end; Result := Code; end else Result := 99; caption := ProgramName + ' -NOT Active'; end; procedure TForm1.Button1Click(Sender: TObject); var i: integer; begin //you can use SW_SHOWNORMAL or SW_HIDE i:=RunProgramWait('c:\WINNT\system32\cmd.exe', '', 0, SW_SHOWNORMAL); if i=0 then showmessage('Normal Termination') else showmessage('Abnormal Termination') end;