Tom
Tom

Reputation: 3034

How can I run a console application within my Delphi console application?

I want my console application to start another console application, display everything this another application wants to display then do something after this another application finishes and exit. Basically:

Writeln('Started');
ShellExecute(0, 'open', 'another.exe', nil, nil, SW_SHOWNORMAL);
Writeln('Finished');

So how can I show all the output from another console app in my console app? I don't want to capture output from another app. I just want another app to execute in the same command line window.

Upvotes: 2

Views: 4108

Answers (1)

Andreas Rejbrand
Andreas Rejbrand

Reputation: 108929

You might want to try something like this:

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  Windows, SysUtils;

var
  cl: string;
  SI: TStartupInfo;
  PI: TProcessInformation;

begin

  cl := 'C:\WINDOWS\System32\ping.exe 127.0.0.1';
  UniqueString(cl);

  try
    try
      writeln('begin');
      FillChar(SI, sizeof(SI), 0);
      FillChar(PI, sizeof(PI), 0);
      SI.cb := sizeof(SI);

      if not CreateProcess(nil, PChar(cl), nil, nil, true, 0, nil, nil, SI, PI) then
        RaiseLastOSError;

      WaitForSingleObject(PI.hProcess, INFINITE);

      CloseHandle(PI.hProcess);
      CloseHandle(PI.hThread);

      writeln('end');
    except
      on E: Exception do
        Writeln(E.ClassName, ': ', E.Message);
    end;
  finally
    Writeln('Complete');
    Readln;
  end;


end.

Upvotes: 6

Related Questions