How can I wait for the command line to finish?

I ran a program with command line options. How can I wait for the completion of work?

+5
source share
5 answers

This is my answer: (Thanks to everyone)

uses ShellAPI;

function TForm1.ShellExecute_AndWait(FileName: string; Params: string): bool;
var
  exInfo: TShellExecuteInfo;
  Ph: DWORD;
begin

  FillChar(exInfo, SizeOf(exInfo), 0);
  with exInfo do
  begin
    cbSize := SizeOf(exInfo);
    fMask := SEE_MASK_NOCLOSEPROCESS or SEE_MASK_FLAG_DDEWAIT;
    Wnd := GetActiveWindow();
    exInfo.lpVerb := 'open';
    exInfo.lpParameters := PChar(Params);
    lpFile := PChar(FileName);
    nShow := SW_SHOWNORMAL;
  end;
  if ShellExecuteEx(@exInfo) then
    Ph := exInfo.hProcess
  else
  begin
    ShowMessage(SysErrorMessage(GetLastError));
    Result := true;
    exit;
  end;
  while WaitForSingleObject(exInfo.hProcess, 50) <> WAIT_OBJECT_0 do
    Application.ProcessMessages;
  CloseHandle(Ph);

  Result := true;

end;
+11
source

If I understand your question correctly, you want to run the program on the command line and capture its output in your application, and not in the console window. To do this, you can read the output using pipe . Here is a sample source code:

Capturing output from a DOS window (command / console)

+7
source

DSiWin32:

sl := TStringList.Create;
if DSiExecuteAndCapture('cmd.exe /c dir', sl, 'c:\test', exitCode) = 0 then
  // exec error
else
  // use sl
sl.Free;
+4

, ,

ParamCount: , .

ParamStr: , . Dephi

, ,

WriteLn: .

ReadLn: . Delphi

+2

, exe , exe , >, .

For example, if you need to run the "dir" command and get its output, you may have a batch file with a name getdir.batthat contains the following:

@echo off
dir c:\users\myuser\*.* > output.txt

you can execute this batch file using the ShellExecute API function. You can read about it http://delphi.about.com/od/windowsshellapi/a/executeprogram.htm

Then you can read the output file, even using something like TStringList:

var
  output: TStringList;
begin
  output := TStringList.Create();
  output.LoadFromFile('output.txt');
  ...
+2
source

All Articles