[Lazarus] Reading and Writing to TProcess

Richard Mace richard.mace at gmail.com
Sat Apr 12 22:32:02 CEST 2014


Hi All,
I have the following code working well with TProcess outputting to a TMemo,
however, what I'd like to do it monitor the output and then when a certain
string is detected, I'd like to feed back to the process. That is, if the
TProcess outputs a question, I'd like to feed back either a "y" or a "n" as
if the user pressed it manually.

Hope that makes sense

Any ideas where to tweak?

Thanks Richard

const
  C_BUFSIZE = 2048;
var
  Hbk: TProcess;
  Buffer: pointer;
  SStream: TStringStream;
  nread: longint;
begin
  Hbk := TProcess.Create(nil);

  // Replace the line below with your own command string
  Hbk.CommandLine := 'c:\windows\system32\cmd.exe /c dir c:\windows\*.*';
  //

  Hbk.Options := [poUsePipes];
  Hbk.Execute;

  // Prepare for capturing output
  Getmem(Buffer, C_BUFSIZE);
  SStream := TStringStream.Create('');

  // Start capturing output
  while Hbk.Running do
  begin
    nread := Hbk.Output.Read(Buffer^, C_BUFSIZE);
    if nread = 0 then
      sleep(100)
    else
      begin
        // Translate raw input to a string
        SStream.size := 0;
        SStream.Write(Buffer^, nread);
        // And add the raw stringdata to the memo
        Memo1.Lines.Text := Memo1.Lines.Text + SStream.DataString;
      end;
  end;

  // Capture remainder of the output
  repeat
    nread := Hbk.Output.Read(Buffer^, C_BUFSIZE);
    if nread > 0 then
    begin
      SStream.size := 0;
      SStream.Write(Buffer^, nread);
      Memo1.Lines.Text := Memo1.Lines.Text + SStream.Datastring;
    end
  until nread = 0;

  // Clean up
  Hbk.Free;
  Freemem(buffer);
  SStream.Free;
end;
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lazarus-ide.org/pipermail/lazarus/attachments/20140412/a01b0224/attachment-0002.html>


More information about the Lazarus mailing list