Run a background program and continue code execution?

I want to run a background application from my Delphi code. The opening application is a DOS-based EXE that displays material in a DOS window. The program will be opened indefinitely until it is closed from the task manager. The current code that I use to open the application is:

procedure CaptureConsoleOutput(const ACommand, AParameters: String; CallBack: TArg<PAnsiChar>);
const
    CReadBuffer = 2400;
var
    saSecurity: TSecurityAttributes;
    hRead: THandle;
    hWrite: THandle;
    suiStartup: TStartupInfo;
    piProcess: TProcessInformation;
    pBuffer: array [0 .. CReadBuffer] of AnsiChar;
    dBuffer: array [0 .. CReadBuffer] of AnsiChar;
    dRead: DWord;
    dRunning: DWord;
begin
    saSecurity.nLength := SizeOf(TSecurityAttributes);
    saSecurity.bInheritHandle := True;
    saSecurity.lpSecurityDescriptor := nil;

    if CreatePipe(hRead, hWrite, @saSecurity, 0) then
    begin
        FillChar(suiStartup, SizeOf(TStartupInfo), #0);
        suiStartup.cb := SizeOf(TStartupInfo);
        suiStartup.hStdInput := hRead;
        suiStartup.hStdOutput := hWrite;
        suiStartup.hStdError := hWrite;
        suiStartup.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
        suiStartup.wShowWindow := SW_HIDE;

        if CreateProcess(nil, pChar(ACommand + ' ' + AParameters), @saSecurity, @saSecurity, True, NORMAL_PRIORITY_CLASS, nil, nil, suiStartup, piProcess) then
        begin
            repeat
                dRunning := WaitForSingleObject(piProcess.hProcess, 100);
                //Application.ProcessMessages();
                repeat
                    dRead := 0;
                    ReadFile(hRead, pBuffer[0], CReadBuffer, dRead, nil);
                    if(dRead > 0) then
                    begin
                      pBuffer[dRead] := #0;
                      //ShowMessage(pBuffer);
                      //OemToAnsi(pBuffer, pBuffer);
                      //Unicode support by Lars Fosdal
                      OemToCharA(pBuffer, dBuffer);
                      CallBack(dBuffer);
                    end;
                until (dRead < CReadBuffer);
            until (dRunning <> WAIT_TIMEOUT);
            CloseHandle(piProcess.hProcess);
            CloseHandle(piProcess.hThread);
        end;
        CloseHandle(hRead);
        CloseHandle(hWrite);
    end;
end;

This is good, however, since the program does not “close” and remains open forever, my application freezes and the code never moves.

Any help would be appreciated

+4
source share
2 answers

, , CreateProcess() , . , , , .

+10

// . :

//, ping Google Server. , Delphi. , File-New -//Other-Thread Object, , .

  TPing = class (TThread)          { }           Execute; ; ;

// CaptureConsoleOutput Thread.

// Execute CaptureConsoleOutput. // Memo.

// !

TPing.Execute;   : = tpLower;   CaptureConsoleOutput ('ping www.yahoo.com', '-t', Form1.Memo2); ;

0

All Articles