计算机二级DELPHI函数:捕获控制台程序输出计算机二级考试
文章作者 100test 发表时间 2009:05:02 15:09:13
来源 100Test.Com百考试题网
2009年下半年全国计算机等级考试你准备好了没?考计算机等级考试的朋友,2009年下半年全国计算机等级考试时间是2009年9月19日至23日。更多优质资料尽在百考试题论坛 百考试题在线题库
本文实现了在Delphi中运行控制台程序,并将控制台程序的输出在Memo控件中显示出来。
工作中需要手工编译J2ME的程序,开始编写了一个批处理程序,但是感觉使用中非常繁琐,于是想用Delphi做一个集成编译工具,但是java的编译工具都是console程序,怎么捕获到console程序的输出,并显示在Memo中呢,查了网上的一些资料,反复测试,找到了一个实现的方法,希望对大家有帮助:
procedure TMainForm.RunDosInMemo(const DosApp: string. AMemo: TMemo).
const
{设置ReadBuffer的大小}
ReadBuffer = 2400.
var
Security: TSecurityAttributes.
ReadPipe, WritePipe: THandle.
start: TStartUpInfo.
ProcessInfo: TProcessInformation.
Buffer: PChar.
BytesRead: DWord.
Buf: string.
begin
with Security do
begin
nlength := SizeOf(TSecurityAttributes).
binherithandle := true.
lpsecuritydescriptor := nil.
end.
{创建一个命名管道用来捕获console程序的输出}
if 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程序}
if 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 string(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.