I have a procedure to capture a hidden Command Prompt window and display the output in a TMemo
. This is the same/similar code that is posted all over the internet and Stack Overflow:
var
Form1: TForm1;
commandline,workdir:string;
implementation
{$R *.dfm}
procedure GetDosOutput;
var
SA: TSecurityAttributes;
SI: TStartupInfo;
PI: TProcessInformation;
StdOutPipeRead, StdOutPipeWrite: THandle;
WasOK: Boolean;
Buffer: array[0..255000] of AnsiChar;
BytesRead: Cardinal;
Handle: Boolean;
thisline,tmpline,lastline:string;
commandstartms:int64;
p1,p2:integer;
begin
with SA do begin
nLength := SizeOf(SA);
bInheritHandle := True;
lpSecurityDescriptor := nil;
end;
CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SA, 0);
try
with SI do
begin
FillChar(SI, SizeOf(SI), 0);
cb := SizeOf(SI);
dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
wShowWindow := SW_HIDE;
hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdin
hStdOutput := StdOutPipeWrite;
hStdError := StdOutPipeWrite;
end;
lastline:='';
Handle := CreateProcess(nil, PWideChar('cmd.exe /C ' + CommandLine),
nil, nil, True, 0, nil,
PWideChar(WorkDir), SI, PI);
CloseHandle(StdOutPipeWrite);
if Handle then
try
repeat
WasOK := ReadFile(StdOutPipeRead, Buffer, 255000, BytesRead, nil);
if BytesRead>0 then
begin
Buffer[BytesRead]:=#0;
Form1.CommandMemo.Lines.BeginUpdate;
thisline:=string(buffer);
Form1.CommandMemo.text:=Form1.CommandMemo.text+thisline;
//auto-scroll to end of memo
SendMessage(Form1.CommandMemo.Handle, EM_LINESCROLL, 0,Form1.CommandMemo.Lines.Count-1);
Form1.CommandMemo.Lines.EndUpdate;
end;
until not WasOK or (BytesRead = 0);
finally
CloseHandle(PI.hThread);
CloseHandle(PI.hProcess);
end;
finally
CloseHandle(StdOutPipeRead);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
commandline:='tree c:';
workdir:='c:\';
GetDosOutput;
end;
That works as expected for any ASCII output but does not support Unicode characters.
When the tree
command runs it normally displays characters like:
│ │ │ │ │ ├───
...but the Memo displays:
³ ³ ³ ÃÄÄÄ
I tried changing the buffer from AnsiChar
to Char
and that does get Unicode displaying in the Memo, but those are just corrupted Unicode characters and not what the command line is showing:
††††‱楦敬猨
潭敶††††‱楦敬猨
潭敶䕈䑁椠潮⁷瑡〠捣攰ㅥ敍杲異汬爠煥敵瑳⌠㤷㔴映潲ⵥ⽷楦浩条ⵥ潤湷捳污汁敲摡⁹灵琠慤整ਮㅥ敍杲異汬爠煥敵††††‱楦敬猨
潭敶††††‱楦敬猨
潭敶ⵥ⽷楦浩条ⵥ潤湷捳污
Can anyone help tweak that code to support times when the command line uses Unicode characters? I have been messing around with this for hours now trying the suggestions below, but none of them get the tree output displaying correctly in the memo. Can anyone can fix my example code here or post code that works with D11?