本文实现了在Delphi中运行控制台并将控制台输出在MemoControl控件中显示出来
工作中需要手工编译J2ME开始编写了个批处理但是感觉使用中非常繁琐于是想用Delphi做个集成编译工具但是java编译工具都是console如何捕获到console输出并显示在Memo中呢查了网上些资料反复测试找到了个实现思路方法希望对大家有帮助:
procedure TMainForm.RunDosInMemo(const DosApp: ; AMemo: TMemo);
const
{设置ReadBuffer大小}
ReadBuffer = 2400;
var
Security: TSecurityAttributes;
ReadPipe, WritePipe: THandle;
start: TStartUpInfo;
ProcessInfo: TProcessInformation;
Buffer: PChar;
BytesRead: DWord;
Buf: ;
begin
with Security do
begin
nlength := SizeOf(TSecurityAttributes);
binherithandle := true;
lpsecuritydescriptor := nil;
end;
{创建个命名管道用来捕获console输出}
Createpipe(ReadPipe, WritePipe, @Security, 0) then
begin
Buffer := AllocMem(ReadBuffer + 1);
FillChar(Start, Sizeof(Start), #0)
{设置console启动属性}
with start do
begin
cb := SizeOf(start);
start.lpReserved := nil;
lpDesktop := nil;
lpTitle := nil;
dwX := 0;
dwY := 0;
dwXSize := 0;
dwYSize := 0;
dwXCountChars := 0;
dwYCountChars := 0;
dwFillAttribute := 0;
cbReserved2 := 0;
lpReserved2 := nil;
hStdOutput := WritePipe; //将输出定向到我们建立WritePipe上
hStdInput := ReadPipe; //将输入定向到我们建立ReadPipe上
hStdError := WritePipe;//将输出定向到我们建立WritePipe上
dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
wShowWindow := SW_HIDE;//设置窗口为hide
end;
try
{创建个子进程运行console}
CreateProcess(nil, PChar(DosApp), @Security, @Security, true,
NORMAL_PRIORITY_CLASS,
nil, nil, start, ProcessInfo) then
begin
{等待进程运行结束}
WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
{关闭输出...开始没有关掉它结果如果没有输出话死掉了}
CloseHandle(WritePipe);
Buf := \';
{读取console输出}
repeat
BytesRead := 0;
ReadFile(ReadPipe, Buffer[0], ReadBuffer, BytesRead, nil);
Buffer[BytesRead] := #0;
OemToAnsi(Buffer, Buffer);
Buf := Buf + (Buffer);
until (BytesRead < ReadBuffer);
SendDebug(Buf);
{按照换行符进行分割并在Memo中显示出来}
while pos(#10, Buf) > 0 do
begin
AMemo.Lines.Add(Copy(Buf, 1, pos(#10, Buf) - 1));
Delete(Buf, 1, pos(#10, Buf));
end;
end;
finally
FreeMem(Buffer);
CloseHandle(ProcessInfo.hProcess);
CloseHandle(ProcessInfo.hThread);
CloseHandle(ReadPipe);
end;
end;
end;
最新评论