I have a situation in which I want to execute a command line from a Delphi application, and I want to capture the output from that command and then display it back to the user.
Using CreateProcess I can successfully execute the command - and I am able to accurately determine when the command has finished. The problem comes in trying to capture the output from the command.
First I tried the simplest thing, which was to append > MyOutput.Txt to the lpCommandLine string to redirect the output to a text file. This worked well when I typed the command line directly at a command prompt, but when the command was initiated through CreateProcess the > and MyOutput.Txt were treated as additional parameters for the command, and the output was not redirected.
So then I tried to play with the STARTINFO area and set up a "handle" to which the output should be redirected. Here are excerpts from my code:
StartInfo.dwFlags := StartInfo.dwFlags + STARTF_UseSTDHandles;
StartInfo.wShowWindow := sw_ShowNormal; // so I can see whether or not output is redirected
StartInfo.hStdInput := 0;
StartInfo.hStdOutput := TTextRec(MsgFile).Handle; // Text file handle
StartInfo.hStdError := 0;
FillChar(ProcsInfo, SizeOf(ProcsInfo), #0);
CreateProcess(nil, @RunProgName, nil, nil,
True, // bInheritHandles
0, // dwCreationFlags - use defaults
nil, // lpEnvironment
The result with the above code is that the output is redirected (it is not displayed in the "DOS" window), but it is not redirected into the MsgFile. In fact, I do not know where it went! Whether or not MsgFile is open within the Delphi application when CreateProcess is executed, the results are the same - output is redirected ... to nowhere? I do not see any error messages (compiler or run-time).
Can anybody help me here? How should I set up hStdOutput so that I can access the output text when the command has finished?