关于控制台重定向!问题解决立刻结贴!
我需要把控制台程序的输出结果重定向到TMemo中。
下面是参考MSDN和其他一些资料写的,但是存在一些问题:
1. 程序不够简练
2. 能不能不让控制台显示出来。我的程序每次在执行时都会产生一个可见的控制台(虽然是一闪而过)。
我对重定向的过程和步骤仍然不是很清楚,望高手指点。
void __fastcall TForm1::SetChildHandles()
{
//TODO: Add your source code here
AllocConsole();
// 保存原始标准句柄
//HANDLE hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(sa);
sa.bInheritHandle = true;
sa.lpSecurityDescriptor = NULL;
if(!CreatePipe(&hParentTemp, &hChildStdOut, &sa, 0))
Application->MessageBoxA("Create pipe error", "error", MB_OK);
DuplicateHandle(GetCurrentProcess(), hParentTemp,
GetCurrentProcess(), &hParentStdout,
0, false,
DUPLICATE_SAME_ACCESS + DUPLICATE_CLOSE_SOURCE);
SetStdHandle(STD_OUTPUT_HANDLE, hChildStdOut);
}
void __fastcall TForm1::Button1Click(TObject *Sender)
{
SetChildHandles();
PROCESS_INFORMATION piChild;
STARTUPINFO Startupinfo;
GetStartupInfo(&Startupinfo);
Startupinfo.dwFlags = STARTF_USESTDHANDLES;
Startupinfo.wShowWindow = SW_HIDE;
Startupinfo.cb = sizeof(Startupinfo);
Startupinfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
Startupinfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
Startupinfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
CreateProcess(NULL, "NETSTAT -a -n",
NULL, NULL,
true, 0,
NULL, NULL,
&Startupinfo, &piChild);
WaitForSingleObject(piChild.hProcess, INFINITE);
AnsiString sOutput, sItem;
char sBuf[4097];
memOutput->Clear();
memOutput->Text = sBuf;
do
{
ReadFile(hParentStdout, sBuf, 4096, &dwRead, NULL);
sOutput += sBuf;
while(sOutput.Pos('\n')>0)
{
sItem = sOutput.SubString(1, sOutput.Pos('\n')-1);
sOutput.Delete(1, sOutput.Pos('\n'));
memOutput->Lines->Add(sItem);
}
}while(dwRead>=4096);
CloseHandle(piChild.hProcess);
FreeConsole();
}