有时候我们需要重定向标准输出(stdout)错误输出(stderr)到编辑控件中:比如我们作了一个前端编译器,编译的功能由mingw gcc来完成,这时我们要捕获它的编译消息到我们的输出窗口,这时怎么办呢!
很简单,我们需要用匿名管道来实现,参见如下代码:
SECURITY_ATTRIBUTES g_sa = {sizeof(SECURITY_ATTRIBUTES),NULL,TRUE};
void CGccDbgView::OnCompiler()
{
// TODO: Add your control notification handler code here
HANDLE hWritePipe, hReadPipe;
if ( !CreatePipe( &hReadPipe, &hWritePipe, &g_sa, 0 ) )
{
return;
}
CString strCmdLine="c:\\gcc.exe test.c";
// create an environment for the CGI process....
DWORD dwCreateFlags = 0;
PROCESS_INFORMATION pi;
STARTUPINFO si = {0};
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.wShowWindow = SW_HIDE;
si.hStdInput = hReadPipe;
si.hStdOutput = hWritePipe;
si.hStdError = hWritePipe;
BOOL bOk = CreateProcess( NULL, strCmdLine.GetBuffer(1),
NULL, NULL, TRUE,
dwCreateFlags, NULL,
"c:\\", &si, &pi );
strCmdLine.ReleaseBuffer();
// if created....
if ( bOk )
{
char buffer[1024]={0};
// wait for either cancel or process done....
WaitForSingleObject(pi.hProcess,INFINITE);
// release our hold on the thread....
CloseHandle( pi.hThread );
// send the body of the post to the stdin....
DWORD dwWritten = 0;
ReadFile( hReadPipe, buffer,1024,&dwWritten, NULL );
m_msg = buffer;
// AfxMessageBox(m_msg);
UpdateData(FALSE);
// close our hold on it....
CloseHandle( pi.hProcess );
}
}
这里m_msg属于编辑器控件变量。这样我们就能在编辑控件中看到结果了。如图: