void __fastcall TForm1::Button1Click(TObject *Sender)
{
SECURITY_ATTRIBUTES sa;
ZeroMemory(&sa,sizeof(SECURITY_ATTRIBUTES));
sa.nLength=sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle=true;
sa.lpSecurityDescriptor=NULL;
HANDLE ReadPipeHandle;
HANDLE WritePipeHandle;
if(!CreatePipe(&ReadPipeHandle,&WritePipeHandle,&sa,0))
RaiseLastWin32Error();
STARTUPINFO si;
ZeroMemory(&si,sizeof(STARTUPINFO));
si.cb=sizeof(STARTUPINFO);
si.dwFlags=STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
si.wShowWindow=SW_HIDE;
si.hStdOutput=WritePipeHandle;
si.hStdError=WritePipeHandle;
PROCESS_INFORMATION pi;
ZeroMemory(&pi,sizeof(PROCESS_INFORMATION));
if(!CreateProcess("YourProgram.exe",NULL,NULL,NULL,true,0,NULL,NULL,&si,&pi))
RaiseLastWin32Error();
char Data[1024];
for (;;)
{
DWORD BytesRead;
DWORD TotalBytes;
DWORD BytesLeft;
if(!PeekNamedPipe(ReadPipeHandle,Data,sizeof(Data),&BytesRead,
&TotalBytes,&BytesLeft))RaiseLastWin32Error();
if(BytesRead)
{
if(!ReadFile(ReadPipeHandle,Data,sizeof(Data)-1,&BytesRead,NULL))
RaiseLastWin32Error();
Data[BytesRead]='\0';
Memo1->Lines->Add(AnsiString(Data));
}
else
{
if(WaitForSingleObject(pi.hProcess,0)==WAIT_OBJECT_0)break;
}
}
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
CloseHandle(ReadPipeHandle);
CloseHandle(WritePipeHandle);
}