avatar

捕获控制台程序的输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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;
Comments ( 0 ) Trackbacks ( 0 ) Leave a Reply
  1. No comments yet.

    目前尚无任何评论.

    コメントはまだありません。

  2.                    
  1. No trackbacks yet.

    目前尚无任何 trackbacks 和 pingbacks.

    トラックバックはまだありません。

  • ☆*:.。. o(≧▽≦)o .。.:*☆
  • _(:з」∠)_
  • ♪(´ε` )
  • ψ(`∇´)ψ
  • (-_-#)
  • (=´∀`)人(´∀`=)
  • \(//∇//)\
  • ♪(*^^)o∀*∀o(^^*)♪
  • (((o(*゚▽゚*)o)))
  • (´・_・`)
  • σ(^_^;)
  • ( *`ω´)
  • (ノ`Д´)ノ
  • (( _ _ ))..zzzZZ
  • ( ̄▽ ̄)
  • ヽ(`Д´#)ノ
  • ((((;゚Д゚)))))))
  • (>_<)
  • (T_T)
  • ( T_T)\(^-^ )
  • ε=ε=ε=ε=ε=ε=┌(; ̄◇ ̄)┘