Hello everybody,

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[1], 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?

Thank you!


Further to the above - more trial and error led me to a workable solution to my own problem:

I included the text CMD /C at the beginning of the lpCommandLine string which also had > MyOutput.Txt at the end. The command interpreter then parsed the command string correctly and the standard outpur was redirected to MyOutput.Txt.

I was not able to get anything working properly using the hStdOuput handle withing the STARTINFO block, but, for my application, now I don't need to!


Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.