可回显的调用方法:
这个方法步骤比较复杂,是通过创建一个新进程来模拟cmd命令行,将写命令行和回显通过管道的方式呈现。
例如:
view plain
1. void CTestMFCDlg::OnOK()
2. {
3. // TODO: Add extra validation here
4. SECURITY_ATTRIBUTES sa;
5. HANDLE hRead,hWrite;
6.
7. sa.nLength = sizeof(SECURITY_ATTRIBUTES);
8. sa.lpSecurityDescriptor = NULL;
9. sa.bInheritHandle = TRUE;
10.
11. if(!CreatePipe(&hRead,&hWrite,&sa,0))
12. {
13. MessageBox("CreatePipe Failed");
14. return;
15. }
16.
17. STARTUPINFO si;
18. PROCESS_INFORMATION pi;
19.
20. ZeroMemory(&si,sizeof(STARTUPINFO));
21. si.cb = sizeof(STARTUPINFO);
22. GetStartupInfo(&si);
23. si.hStdError = hWrite;
24. si.hStdOutput = hWrite;
25. si.wShowWindow = SW_HIDE;
26. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
27.
28. char cmdline[200];
29. CString tmp,stredit2;
30. GetDlgItemText(IDC_EDIT_CMD,stredit2);
31. tmp.Format("cmd /C %s",stredit2);
32. sprintf(cmdline,"%s",tmp);
33.
34. if(!CreateProcess(NULL,cmdline,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi))
35. {
36. MessageBox("CreateProcess failed!");
37. return;
38. }
39. CloseHandle(hWrite);
40.
41. char buffer[4096] = {0};
42. CString strOutput;
43. DWORD bytesRead;
44.
45. while(1)
46. {
47. if(NULL == ReadFile(hRead,buffer,4095,&bytesRead,NULL))
48. {
49. break;
50. }
51. strOutput += buffer;
52. SetDlgItemText(IDC_EDIT_TEXT,strOutput);
53. UpdateWindow();
54. Sleep(1000);
55. }
56. CloseHandle(hRead);
57.}
以上是在一个MFC中点击OnOK按钮后,将IDC_EDIT_CMD编辑框中的命令执行,并将1秒内cmd命令的回显答应到IDC_EDIT_TEXT编辑框中的实现。