[Delphi XE4, Win 7]
At startup my GUI application spawns a visible 'cmd.exe' console window (using 'CreateProcess'). The console is up as long as the GUI app is running.
The console window expects input from the keyboard, but the input/command has to come from the GUI app (the GUI sends the command to be executed to the console, and the user can watch what's happening in the console window - so no console output redirection). I tried to use an anon pipe for sending commands to the console (stdin redirected), but it doesn't work. Code snippet :
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
Fsa: SECURITY_ATTRIBUTES;
Fsi: STARTUPINFO;
Fpi: PROCESS_INFORMATION;
Fpipe_stdin_read : THandle;
Fpipe_stdin_write: THandle;
procedure CreateProcessCmd;
end;
...
procedure TForm1.Button1Click(Sender: TObject);
begin
// write command to pipe
WriteFile(Fpipe_stdin_write, ...);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
CreateProcessCmd;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
CloseHandle(Fpi.hProcess);
CloseHandle(Fpi.hThread);
CloseHandle(Fpipe_stdin_read);
CloseHandle(Fpipe_stdin_write);
inherited;
end;
procedure TForm1.CreateProcessCmd;
begin
// init security structure
Fsa.nLength := SizeOf(SECURITY_ATTRIBUTES);
Fsa.bInheritHandle := True;
Fsa.lpSecurityDescriptor := nil;
// create a pipe for the child process's stdin
if not CreatePipe(Fpipe_stdin_read, Fpipe_stdin_write, @Fsa, 0) then
begin
...;
Exit;
end;
// init startup info structure
FillChar(Fsi, SizeOf(STARTUPINFO), #0);
Fsi.cb := SizeOf(STARTUPINFO);
Fsi.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW or STARTF_USEPOSITION;
Fsi.hStdError := GetStdHandle(STD_ERROR_HANDLE); // don't redirect std err
Fsi.hStdOutput := GetStdHandle(STD_OUTPUT_HANDLE); // don't redirect std out
Fsi.hStdInput := Fpipe_stdin_read;
Fsi.wShowWindow := SW_SHOW;
Fsi.dwX := 1000;
Fsi.dwY := 50;
// init process info structure
FillChar(Fpi, SizeOf(PROCESS_INFORMATION), #0);
// create process with new console
if not CreateProcess(nil,PChar(GetEnvironmentVariable('COMSPEC')),nil,nil,True,CREATE_NEW_CONSOLE,nil,nil,Fsi,Fpi) then
...;
end;
The cmd console window will be created but immediately closed after that. Without the redirecting code parts the console is up and running (expecting keyboard input, of course).
What am I doing wrong? Any insight / working code is really appreciated.
Note: A similiar question has already been asked (How to send command to console application from GUI application) but that one works with capturing/redirecting the console output - in my case this is not an option, the output generated after sending a command has to be displayed in the console window.