4.CreateProcess
/*------------cmd 回显----------*/ SECURITY_ATTRIBUTES sa; HANDLE hRead,hWrite; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = NULL; //使用系统默认的安全描述符 sa.bInheritHandle = TRUE; //创建的进程继承句柄 if (!CreatePipe(&hRead,&hWrite,&sa,0)) //创建匿名管道 { MessageBox("CreatePipe Failed!","提示",MB_OK | MB_ICONWARNING); return; } STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si,sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); GetStartupInfo(&si); si.hStdError = hWrite; si.hStdOutput = hWrite; //新创建进程的标准输出连在写管道一端 si.wShowWindow = SW_HIDE; //隐藏窗口 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; char cmdline[200]; CString tmp,stredit2; GetDlgItemText(IDC_EDIT_CMD,stredit2); //获取编辑框中输入的命令行 tmp.Format("cmd /C %s",stredit2); sprintf(cmdline,"%s",tmp); if (!CreateProcess(NULL,cmdline,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi)) //创建子进程 { MessageBox("CreateProcess Failed!","提示",MB_OK | MB_ICONWARNING); return; } CloseHandle(hWrite); //关闭管道句柄 char buffer[4096] = {0}; CString strOutput; DWORD bytesRead; while (true) { if (ReadFile(hRead,buffer,4095,&bytesRead,NULL) == NULL) //读取管道 break; strOutput += buffer; SetDlgItemText(IDC_EDIT_OUTPUT,strOutput); //显示输出信息到编辑框,并刷新窗口 UpdateWindow(); Sleep(100); } CloseHandle(hRead);