unit uConsole;
interface
uses
SysUtils, Classes, Windows;
procedure GetConsoleOutput (const CommandLine : string; var Output : TStringList);
implementation
procedure GetConsoleOutput (const CommandLine : string; var Output : TStringList);
var
SA: TSecurityAttributes;
SI: TStartupInfo;
PI: TProcessInformation;
StdOutFile, AppProcess, AppThread : THandle;
RootDir, WorkDir, StdOutFileName:string;
const
FUNC_NAME = 'GetConsoleOuput';
begin
StdOutFile:=0;
AppProcess:=0;
AppThread:=0;
try
// Initialize dirs
RootDir := ExtractFilePath(ParamStr(0));
WorkDir := RootDir;
// Initialize output file security attributes
FillChar(SA,SizeOf(SA),#0);
SA.nLength:=SizeOf(SA);
SA.lpSecurityDescriptor:=nil;
SA.bInheritHandle:=True;
// Create Output File
StdOutFileName := RootDir+'output.tmp';
StdOutFile := CreateFile(PChar(StdOutFileName),
GENERIC_READ or GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE,
@SA,
CREATE_ALWAYS, // Always create it
FILE_ATTRIBUTE_TEMPORARY or // Will cache in memory
// if possible
FILE_FLAG_WRITE_THROUGH,
0);
// Check Output Handle
if StdOutFile = INVALID_HANDLE_VALUE then
raise Exception.CreateFmt('Function %s() failed!' + #10#13 +
'Command line = %s',[FUNC_NAME,CommandLine]);
// Initialize Startup Info
FillChar(SI,SizeOf(SI),#0);
with SI do
begin
cb:=SizeOf(SI);
dwFlags:=STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
wShowWindow:=SW_HIDE;
hStdInput:=GetStdHandle(STD_INPUT_HANDLE);
hStdError := StdOutFile;
hStdOutput:= StdOutFile;
end;
// Create the process
if CreateProcess(nil, PChar(CommandLine), nil, nil, True, 0, nil, PChar(WorkDir), SI, PI) then
begin
WaitForSingleObject(PI.hProcess,INFINITE);
AppProcess:=PI.hProcess;
AppThread:=PI.hThread;
end
else
raise Exception.CreateFmt('CreateProcess() in function %s() failed!'
+ #10#13 + 'Command line = %s',[FUNC_NAME,CommandLine]);
CloseHandle(StdOutFile);
StdOutFile:=0;
Output.Clear;
Output.LoadFromFile (StdOutFileName);
// Clean Console output
Output.Text := StringReplace(Output.Text,#13#10#13#10,#13#10,[rfReplaceAll, rfIgnoreCase]);
finally
// Close handles
if StdOutFile <> 0 then CloseHandle(StdOutFile);
if AppProcess <> 0 then CloseHandle(AppProcess);
if AppThread <> 0 then CloseHandle(AppThread);
// Delete Output file
if FileExists(StdOutFileName) then
SysUtils.DeleteFile(StdOutFileName);
end;
end;
end.