U
updaite
Программа выводить текст с консоли в Memo, но только после завершения консольного приложения.
Как сделать вывод в реальном времени?
Как сделать вывод в реальном времени?
C++:
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
#define READ_BUFFER_SIZE 1024
String AppName = "E:\\1.exe"; // Консольное приложение
SECURITY_ATTRIBUTES Security;
HANDLE ReadPipe, WritePipe;
STARTUPINFO Start;
TProcessInformation ProcessInfo;
char *Buffer, Data;
DWORD BytesRead, Apprunning;
int Result, DataSize;
Security.nLength = sizeof(TSecurityAttributes);
Security.bInheritHandle = true;
Security.lpSecurityDescriptor = NULL;
if (CreatePipe(&ReadPipe, &WritePipe, &Security, 0))
{
Buffer = new char[READ_BUFFER_SIZE + 1];
memset(&Start, 0, sizeof(Start));
Start.cb = sizeof(Start);
Start.hStdOutput = WritePipe;
Start.hStdInput = ReadPipe;
Start.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
Start.wShowWindow = SW_HIDE;
if (CreateProcess(NULL, AppName.c_str(), &Security, &Security, true, NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE, NULL, NULL, &Start, &ProcessInfo))
{
do
{
Apprunning = WaitForSingleObject(ProcessInfo.hProcess, 100);
Application->ProcessMessages();
// вычитываем данные работающей консоли
do
{
Result = PeekNamedPipe(ReadPipe, NULL, 0, NULL, (LPDWORD) &DataSize, NULL);
if ((Result) && (DataSize))
{
if (DataSize > READ_BUFFER_SIZE) DataSize = READ_BUFFER_SIZE;
ReadFile(ReadPipe, Buffer, DataSize, &BytesRead, NULL);
Buffer[BytesRead] = 0;
OemToAnsi(Buffer, Buffer);
Memo->Text = Memo->Text + (AnsiString) Buffer;
}
}
while ((Result) && (DataSize));
}
while (Apprunning == WAIT_TIMEOUT);
}
delete [] Buffer;
CloseHandle(ProcessInfo.hProcess);
CloseHandle(ProcessInfo.hThread);
CloseHandle(ReadPipe);
CloseHandle(WritePipe);
}
}