在Delphi中捕獲控制臺程序的輸出

字號:

本文實現(xiàn)了在Delphi中運行控制臺程序,并將控制臺程序的輸出在Memo控件中顯示出來。
    工作中需要手工編譯J2ME的程序,開始編寫了一個批處理程序,但是感覺使用中非常繁瑣,于是想用Delphi做一個集成編譯工具,但是java的編譯工具都是console程序,怎么捕獲到console程序的輸出,并顯示在Memo中呢,查了網(wǎng)上的一些資料,反復(fù)測試,找到了一個實現(xiàn)的方法,希望對大家有幫助:
    procedure TMainForm.RunDosInMemo(const DosApp: string; AMemo: TMemo);
    const
    {設(shè)置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;
    {創(chuàng)建一個命名管道用來捕獲console程序的輸出}
    if Createpipe(ReadPipe, WritePipe, @Security, 0) then
    begin
    Buffer := AllocMem(ReadBuffer + 1);
    FillChar(Start, Sizeof(Start), #0)
    {設(shè)置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;