I'm using the code below to send commands to a console application and receive its output in a string.
Everything works well except the console application doesn't have a command to close or exit. Only by using Ctrl-C to stop/close (finish the job and close properly). I'm stuck here how I can send that key events to the console.
This is the code inside a thread.
procedure DoWork.Execute;
const
MAX_CHUNK: dword = 4096;
var
Buffer: array [0..MaxBufferSize] of byte;
SecurityAttributes: SECURITY_ATTRIBUTES;
hiRead, hoRead, hiWrite, hoWrite: THandle;
StartupInfo: TSTARTUPINFO;
BytesRead, BytesWritten, ExitCode, PipeMode: dword;
ComSpec:array [0..MAX_PATH] of char;
ToSend, Tempstr,WorkDir,cmd2,fsize: string;
i,acc: integer;
c: cardinal;
begin
cmd2 := 'rtmpdump.exe --live -v -r "rtmp://"' ;
WorkDir := 'C:\Users\Administrator\Desktop\rtmpdump';
SecurityAttributes.nLength := SizeOf(SECURITY_ATTRIBUTES);
SecurityAttributes.lpSecurityDescriptor := nil;
SecurityAttributes.bInheritHandle := True;
CreatePipe(hiRead, hiWrite, @SecurityAttributes, 0);
CreatePipe(hoRead, hoWrite, @SecurityAttributes, 0);
GetStartupInfo(StartupInfo);
StartupInfo.hStdOutput := hoWrite;
StartupInfo.hStdError := hoWrite;
StartupInfo.hStdInput := hiRead;
StartupInfo.dwFlags := STARTF_USESHOWWINDOW + STARTF_USESTDHANDLES;
StartupInfo.wShowWindow := SW_HIDE;
// GetEnvironmentVariable('COMSPEC', ComSpec, sizeof(ComSpec));
CreateProcess(nil, PChar('C:\Users\Administrator\Desktop\rtmpdump\rtmpdump.exe ' + cmd2),
nil, nil, True,CREATE_NEW_CONSOLE, nil,
PChar(WorkDir), StartupInfo, ProcessInfo);
CloseHandle(hoWrite);
CloseHandle(hiRead);
PipeMode := PIPE_NOWAIT;
SetNamedPipeHandleState(hoRead, PipeMode , nil, nil);
while true do
begin
Sleep(10);
GetExitCodeProcess(ProcessInfo.hProcess, ExitCode);
if ExitCode <> STILL_ACTIVE then Break;
ReadFile(hoRead, Buffer, MAX_CHUNK, BytesRead, nil);
if BytesRead > 0 then
begin
for i := 0 to BytesRead - 1 do
TempStr := Tempstr + string(char(buffer[i]));
end else
begin
if TempStr <> '' then
begin
try
except
break;
end;
TempStr := '';
end;
end;
if comand <> '' then
begin
WriteFile(hiWrite, pchar(Comando)^, length(comando), BytesWritten, nil);
WriteFile(hiWrite, #13#10, 2, BytesWritten, nil);
comando := '';
end;
end;
GetExitCodeProcess(ProcessInfo.hProcess, ExitCode);
if ExitCode = STILL_ACTIVE then TerminateProcess(ProcessInfo.hProcess, 0);
CloseHandle(hoRead);
CloseHandle(hiWrite);
end;
PS: I have tried -> generateconsolectrlevent