贴一段代码给你,支持向控制台输入和输出内容:
unit RedirectConsole;
interface
const
CRLF=#13#10;
var
RC_SendBuf:string;
RC_End:Boolean;
RC_ExitCode:Cardinal;
procedure RC_Run(Command:string);
procedure RC_LineIn(s:string);
var
RC_LineOut
rocedure(s:string);
implementation
uses Windows,Forms;
procedure RC_LineIn(s:string);
begin
RC_SendBuf:=RC_SendBuf+s+CRLF;
end;// RC_LineIn;
procedure SplitLines(s:string);
var
t:string;
begin
while Pos(CRLF,s)<>0 do
begin
t:=Copy(s,1,Pos(CRLF,s)-1);
RC_LineOut(t);
Delete(s,1,Pos(CRLF,s)+1);
end;
if Length(s)>0 then RC_LineOut(s);
end;// SplitLines
procedure RC_Run(Command:string);
const
bufsize=1024;// 1KByte buffer
var
buf:array[0..bufsize-1] of char;
si:tSTARTUPINFO;
sa:tSECURITYATTRIBUTES;
sd:tSECURITYDESCRIPTOR;
Pi:tPROCESSINFORMATION;
newstdin,newstdout,read_stdout,write_stdin:tHandle;
bread,avail:dword;
begin
// Configuraciones de seguridad para WinNT
InitializeSecurityDescriptor(@sd,SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(@sd,True,nil,False);
sa.lpSecurityDescriptor:=@sd;
// Creamos Pipe A
if not CreatePipe(newstdin,write_stdin,@sa,0) then
begin
RC_LineOut('Error creating Pipe A');
Exit;
end;
// Creamos Pipe B
if not CreatePipe(read_stdout,newstdout,@sa,0) then
begin
RC_LineOut('Error creating Pipe B');
CloseHandle(newstdin);
CloseHandle(write_stdin);
Exit;
end;
// Configuramos si
GetStartupInfo(si);
si.dwFlags:=STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
si.wShowWindow:=SW_HIDE;
si.hStdOutput:=newstdout;
si.hStdError:=newstdout;
si.hStdInput:=newstdin;
// Creamos proceso
if not CreateProcess(pchar(Command),nil,nil,nil,True,
CREATE_NEW_CONSOLE,nil,nil,si,Pi) then
begin
RC_LineOut('Error creating process: '+Command);
CloseHandle(newstdin);
CloseHandle(newstdout);
CloseHandle(read_stdout);
CloseHandle(write_stdin);
Exit;
end;
// Loop principal
FillChar(buf,SizeOf(buf),0);
RC_End:=False;
RC_SendBuf:='';
repeat
// application.processmessages;
Application.HandleMessage;
GetExitCodeProcess(Pi.hProcess,RC_ExitCode);
if (RC_ExitCode<>STILL_ACTIVE) then RC_End:=True;
PeekNamedPipe(read_stdout,@buf,bufsize,@bread,@avail,nil);
// Comprobamos texto de salida
if (bread<>0) then
begin
FillChar(buf,bufsize,0);
if (avail>bufsize) then
while (bread>=bufsize) do
begin
ReadFile(read_stdout,buf,bufsize,bread,nil);
SplitLines(buf);
FillChar(buf,bufsize,0);
end
else
begin
ReadFile(read_stdout,buf,bufsize,bread,nil);
SplitLines(buf);
end;
end;
// Comprobamos texto de entrada
while (Length(RC_SendBuf)>0) do
begin
WriteFile(write_stdin,RC_SendBuf[1],1,bread,nil);
Delete(RC_SendBuf,1,1);
end;
until RC_End;
// Cerramos las cosas
CloseHandle(Pi.hThread);
CloseHandle(Pi.hProcess);
CloseHandle(newstdin);
CloseHandle(newstdout);
CloseHandle(read_stdout);
CloseHandle(write_stdin);
end;// RC_Run
end.