在MFC中如果要使用控制台指令,但并不希望弹出控制台窗口,并且可以获取控制台输出,可以用这个函数来实现
void RunCMD(TCHAR *pLog,TCHAR *pCmd)
{
SECURITY_ATTRIBUTES sa;
BOOL ret;
sa.nLength=256;
sa.lpSecurityDescriptor=0;
sa.bInheritHandle=TRUE;
HANDLE hReadPipe1,hWritePipe1,hReadPipe2,hWritePipe2;
ret=CreatePipe(&hReadPipe1,&hWritePipe1,&sa,0);//创建两个匿名管道
ret=CreatePipe(&hReadPipe2,&hWritePipe2,&sa,0);
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si,sizeof(si));
si.cb = sizeof(si);
si.dwFlags=STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
si.wShowWindow=SW_HIDE;
si.hStdInput=hReadPipe2;
si.hStdOutput=si.hStdError=hWritePipe1;
ZeroMemory( &pi,sizeof(pi));
unsigned long lBytesRead;
char Buff[1024]={0};
CString strLog;
CreateProcess(NULL,pCmd,NULL,NULL,TRUE,0,NULL,NULL,&si,&pi);
while(1)
{
ret=PeekNamedPipe(hReadPipe1,Buff,1024,&lBytesRead,0,0);//管道是否有数据可读
if(lBytesRead&&pLog)
{
ret=ReadFile(hReadPipe1,Buff,lBytesRead,&lBytesRead,0);//读取管道里的数据
if(!ret)
break;
strLog.Format(_T("%S"),Buff);
StrCpy(pLog,strLog.GetBuffer());
}
else
break;
}
// WaitForSingleObject( pi.hProcess, INFINITE );
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
这样就可以隐藏调用控制台命令了