使用管道实现读取DOS命令结果,界面如下:
主要代码如下:
1 UpdateData(TRUE); 2 3 //创建一个管道,用于接收命令执行结果 4 SECURITY_ATTRIBUTES sa; 5 ZeroMemory(&sa, sizeof(sa)); 6 sa.nLength = sizeof(SECURITY_ATTRIBUTES); 7 sa.bInheritHandle = TRUE; 8 sa.lpSecurityDescriptor = NULL; 9 HANDLE hRead, hWrite; 10 if (!CreatePipe(&hRead, &hWrite, &sa, 0)) 11 { 12 AfxMessageBox(_T("创建管道出错。")); 13 return; 14 } 15 16 //创建一个没有DOS命令框的、隐藏窗口的进程来执行用户输入的命令 17 STARTUPINFO si; 18 ZeroMemory(&si, sizeof(si)); 19 si.cb = sizeof(STARTUPINFO); 20 GetStartupInfo(&si); 21 si.hStdError = hWrite; 22 si.hStdOutput = hWrite; 23 si.wShowWindow = SW_HIDE; 24 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; 25 26 PROCESS_INFORMATION pi; 27 CString strCommand; 28 strCommand.Format(_T("cmd.exe /c %s"), m_strCommand); 29 BOOL res = CreateProcess(NULL, strCommand.GetBuffer(0), NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi); 30 if (!res) 31 { 32 AfxMessageBox(_T("创建进程出错。")); 33 return; 34 } 35 CloseHandle(hWrite); 36 37 //从管道中读取已写入的数据,并显示出来 38 CString strTemp; 39 TCHAR szBuff[4096] = { 0 }; 40 DWORD dwRead = 0; 41 m_strResult = _T(""); 42 while (true) 43 { 44 if (!ReadFile(hRead, szBuff, 4095, &dwRead, NULL)) 45 { 46 break; 47 } 48 szBuff[dwRead] = _T('\0'); 49 strTemp.Format(_T("%s"), szBuff); 50 m_strResult += strTemp; 51 } 52 UpdateData(FALSE);