How can I wait for a command-line program to finis

2019-01-25 18:16发布

I have run program with command-line parameters. How can i wait for it to finish running?

5条回答
相关推荐>>
2楼-- · 2019-01-25 18:53

If I understand your question correctly, you want to execute program in command-line and capture its output in your application rather than in console window. To do so, you can read the output using pipes. Here is an example source code:

Capture the output from a DOS (command/console) Window

查看更多
一纸荒年 Trace。
3楼-- · 2019-01-25 18:57

If what you want is to execute a command-line executable, and get the response that this exe writes to the console, the easiest way could be to call the exe from a batch file and redirect the output to another file using >, and then read that file.

For example, if you need to execute the "dir" command and get its output you could have a batch file called getdir.bat that contains the following:

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

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

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

var
  output: TStringList;
begin
  output := TStringList.Create();
  output.LoadFromFile('output.txt');
  ...
查看更多
Deceive 欺骗
4楼-- · 2019-01-25 19:01

This is my answer : (Thank you all)

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;
查看更多
Root(大扎)
5楼-- · 2019-01-25 19:02

Using DSiWin32:

sl := TStringList.Create;
if DSiExecuteAndCapture('cmd.exe /c dir', sl, 'c:\test', exitCode) = 0 then
  // exec error
else
  // use sl
sl.Free;
查看更多
【Aperson】
6楼-- · 2019-01-25 19:09

Ok, getting the command-line parameters, you use

ParamCount : returns the number of parameters passed to the program on the command-line.

ParamStr : returns a specific parameter, requested by index. Running Dephi Applications With Parameters

Now, if what you meant is reading and writing to the console, you use

WriteLn : writes a line of text to the console.

ReadLn : reads a line of text from the console as a string. Delphi Basics

查看更多
登录 后发表回答