捕获Dos窗口进度

时间:2018-06-11 11:18:15

标签: windows delphi winapi delphi-xe2 delphi-xe

我正在使用我的问题末尾的代码来捕获dos应用程序的输出。

我尝试捕获下面7z.exe命令的输出:

7z.exe x -y" C:\ Linux.iso" -o" E:\"

7z.exe在其dos窗口结束时显示进度,例如%14 ..,%15 ...,%16 ......但它没有为每个进度添加新行。它正在更新dos输出窗口的最后一行。因此,dos窗口的最后一行更改为%14 ..,%15 ..,..和100%。

我无法捕获这个%14 ..,%15,%16 ..进度。我想找几天的解决方案。如何捕获此进度文本?

-

注意:代码正在运行,并使用ping:

等命令捕获输出

ping 127.0.0.1

问题是捕获dos窗口的输出,该输出没有添加新行,更新了一行。

// Source: https://thundaxsoftware.blogspot.com/2012/12/capturing-console-output-with-delphi.html#comment-form_7827048960744956444
//
// @Author: Jordi Corbilla
// (c) Copyright by Jordi Corbilla.
// Anonymous procedure approach by Lars Fosdal

type
    TArg<T> = reference to procedure(const Arg: T);

procedure TForm1.CaptureConsoleOutput(const ACommand, AParameters: String; CallBack: TArg<PAnsiChar>);
const
  CReadBuffer = 2400;
var
  saSecurity: TSecurityAttributes;
  hRead: THandle;
  hWrite: THandle;
  suiStartup: TStartupInfo;
  piProcess: TProcessInformation;
  pBuffer: array [0 .. CReadBuffer] of AnsiChar;
  dBuffer: array [0 .. CReadBuffer] of AnsiChar;
  dRead: DWORD;
  dRunning: DWORD;
  dAvailable: DWORD;
begin
  saSecurity.nLength := SizeOf(TSecurityAttributes);
  saSecurity.bInheritHandle := true;
  saSecurity.lpSecurityDescriptor := nil;
  if CreatePipe(hRead, hWrite, @saSecurity, 0) then
    try
      FillChar(suiStartup, SizeOf(TStartupInfo), #0);
      suiStartup.cb := SizeOf(TStartupInfo);
      suiStartup.hStdInput := hRead;
      suiStartup.hStdOutput := hWrite;
      suiStartup.hStdError := hWrite;
      suiStartup.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
      suiStartup.wShowWindow := SW_HIDE;
      if CreateProcess(nil, PChar(ACommand + ' ' + AParameters), @saSecurity, @saSecurity, true, NORMAL_PRIORITY_CLASS, nil, nil, suiStartup,
        piProcess) then
        try
          repeat
            dRunning := WaitForSingleObject(piProcess.hProcess, 100);
            PeekNamedPipe(hRead, nil, 0, nil, @dAvailable, nil);
            if (dAvailable > 0) then
              repeat
                dRead := 0;
                ReadFile(hRead, pBuffer[0], CReadBuffer, dRead, nil);
                pBuffer[dRead] := #0;
                OemToCharA(pBuffer, dBuffer);
                CallBack(dBuffer);
              until (dRead < CReadBuffer);
            Application.ProcessMessages;
          until (dRunning <> WAIT_TIMEOUT);
        finally
          CloseHandle(piProcess.hProcess);
          CloseHandle(piProcess.hThread);
        end;
    finally
      CloseHandle(hRead);
      CloseHandle(hWrite);
    end;
end;

0 个答案:

没有答案