获取控制台程序(Console)的输出内容

int GetConsoleExeOutPutCreatePipeAndCreateProcess( char * pstrExename_pstrCmdLine )
{
HANDLE hRead1, hWrite1;   //读句柄,写句柄
HANDLE hRead2, hWrite2;   //读句柄,写句柄
HANDLE hCmd;


int ret;


SECURITY_ATTRIBUTES sa;
sa.nLength              = 12;
sa.lpSecurityDescriptor = 0;
sa.bInheritHandle       = true;


ret = CreatePipe( &hRead1, &hWrite1, &sa, 0 );

if ( ret == 0 )
{
return -1;
}

ret = CreatePipe( &hRead2, &hWrite2, &sa, 0 );

if ( ret == 0 )
{
return -1;
}

//创建进程且重定向标准输入输出

//将其标准输入设置为hReadPipe2
//将其标准输出和错误输出设置为hWritePipe1
STARTUPINFOA si;
ZeroMemory(&si,sizeof(si));
si.dwFlags     = STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
si.wShowWindow = SW_SHOW;
si.hStdInput   = hRead2;
si.hStdOutput  = si.hStdError = hWrite1;
char cmdLine[] = "L:\\ffmpeg.exe -i L:\\t.mp4 L:\\t.avi" ;

PROCESS_INFORMATION ProcessInformation;
ret=CreateProcessA( NULL,  cmdLine, NULL, NULL, 1, 0, NULL, NULL, &si, &ProcessInformation );
if (ret == 0)
{
return -1;
}

//
DWORD lBytesRead;
char buffer[1024] = {0};
bool bCovBegin = false;
while(true)
{
memset(buffer,0,1024);
ret=ReadFile(hRead1,buffer,1023,&lBytesRead,0);
if (ret == 0)
{
break;
}
else
{
AfxMessageBox( CString(buffer) );
}
}


//
CloseHandle(hRead1);
CloseHandle(hWrite1);
CloseHandle(hWrite2);
CloseHandle(hRead2);

// Close process and thread handles. 
CloseHandle( ProcessInformation.hProcess );
CloseHandle( ProcessInformation.hThread );


}



微软的一篇文章:https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx


用Java实现,更简单;

你可能感兴趣的:(VC++)