1BOOL CDOSDlg::ExecDosCmd()
2{
3#define EXECDOSCMD "dir c:" //可以换成你的命令
4
5SECURITY_ATTRIBUTES sa;
6HANDLE hRead,hWrite;
7
8sa.nLength = sizeof(SECURITY_ATTRIBUTES);
9sa.lpSecurityDescriptor = NULL;
10sa.bInheritHandle = TRUE;
11if (!CreatePipe(&hRead,&hWrite,&sa,0))
12{
13 return FALSE;
14}
15char command[1024]; //长达1K的命令行,够用了吧
16strcpy(command,"Cmd.exe /C ");
17strcat(command,EXECDOSCMD);
18STARTUPINFO si;
19PROCESS_INFORMATION pi;
20si.cb = sizeof(STARTUPINFO);
21GetStartupInfo(&si);
22si.hStdError = hWrite; //把创建进程的标准错误输出重定向到管道输入
23si.hStdOutput = hWrite; //把创建进程的标准输出重定向到管道输入
24si.wShowWindow = SW_HIDE;
25si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
26//关键步骤,CreateProcess函数参数意义请查阅MSDN
27if (!CreateProcess(NULL, command,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi))
28{
29 CloseHandle(hWrite);
30 CloseHandle(hRead);
31 return FALSE;
32}
33CloseHandle(hWrite);
34
35char buffer[4096] = {0}; //用4K的空间来存储输出的内容,只要不是显示文件内容,一般情况下是够用了。
36DWORD bytesRead;
37while (true)
38{
39if (ReadFile(hRead,buffer,4095,&bytesRead,NULL) == NULL)
40 break;
41//buffer中就是执行的结果,可以保存到文本,也可以直接输出
42AfxMessageBox(buffer); //这里是弹出对话框显示,保存到文件的话自己改一下吧
43}
44CloseHandle(hRead);
45return TRUE;
46}
47
引用地址:http://www.yxl8.net/htmlVer2/news/detail.asp?id=1430