主要原理是:利用管道重定向输出到buffer中
{
wchar_t exeFullPath[MAX_PATH]={0};
GetModuleFileName(NULL,exeFullPath,MAX_PATH);
wstring strExeFullPath = exeFullPath;
int exePos = strExeFullPath.find_last_of(L"\\");
strExeFullPath = strExeFullPath.substr(0,exePos)+L"\\jyt_ffmpeg.exe";
SECURITY_ATTRIBUTES sa;
HANDLE hRead,hWrite;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
if (!CreatePipe(&hRead,&hWrite,&sa,0))
{
return FALSE;
}
wchar_t command[1024];
swprintf_s(command,1024,L"%s%s%s%s",L"Cmd.exe /C ",strExeFullPath.c_str(),L" -i ",strFilePath.c_str());
STARTUPINFO si;
PROCESS_INFORMATION pi;
si.cb = sizeof(STARTUPINFO);
GetStartupInfo(&si);
si.hStdError = hWrite; //把创建进程的标准错误输出重定向到管道输入
si.hStdOutput = hWrite; //把创建进程的标准输出重定向到管道输入
si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
//关键步骤,CreateProcess函数参数意义请查阅MSDN
if (!CreateProcess(NULL, command,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi))
{
CloseHandle(hWrite);
CloseHandle(hRead);
return FALSE;
}
CloseHandle(hWrite);
char buffer[4095] = {0}; //用4K的空间来存储输出的内容,只要不是显示文件内容,一般情况下是够用了。
DWORD bytesRead;
//FILE* pfile = fopen("c:/00.txt","w+");
while (true)
{
if (ReadFile(hRead,buffer,4095,&bytesRead,NULL) == NULL)
break;
//fwrite(buffer,1,strlen(buffer),pfile);
string str = buffer;
CCommonInterface comm;
wstring strW = comm.AnsiToU((char*)str.c_str());
wstring durStr = L"Duration: ";
int pos = strW.find(durStr.c_str());
if (pos>0){
pos += durStr.length();
strW = strW.substr(pos,8);
string strAnsi = comm.UtoAnsi(strW.c_str());
//fwrite(strAnsi.c_str(),1,strlen(strAnsi.c_str()),pfile);
}
}
//fclose(pfile);
CloseHandle(hRead);
return TRUE;
}