Mega Code Archive

 
Categories / Delphi / Examples
 

Execute an external application and wait its end

Title: Execute an external application and wait its end Question: How can I execute an external program and wait its end? Answer: With this code we can execute an external application and wait its end. function ExecAndWait(const FileName, Params: ShortString; const WinState: Word): boolean; export; var StartInfo: TStartupInfo; ProcInfo: TProcessInformation; CmdLine: ShortString; begin { Put the name of file between quotes, due to spaces in names of files in system Win9x } CmdLine := '"' + Filename + '" ' + Params; FillChar(StartInfo, SizeOf(StartInfo), #0); with StartInfo do begin cb := SizeOf(SUInfo); dwFlags := STARTF_USESHOWWINDOW; wShowWindow := WinState; end; Result := CreateProcess(nil, PChar( String( CmdLine ) ), nil, nil, false, CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, PChar(ExtractFilePath(Filename)),StartInfo,ProcInfo); { Wait the finish of program } if Result then begin WaitForSingleObject(ProcInfo.hProcess, INFINITE); { Free the Handles } CloseHandle(ProcInfo.hProcess); CloseHandle(ProcInfo.hThread); end; end; PS: This code was tested in delphi versions 3, 4 and 5.