#define EXECDOSCMD "ping
www.sohu.com" //可以换成你的命令
BOOL ExecDosCmd()
{
SECURITY_ATTRIBUTES sa;
HANDLE hRead,hWrite;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
if (!CreatePipe(&hRead,&hWrite,&sa,0))
{
return FALSE;
}
STARTUPINFO si;
PROCESS_INFORMATION pi;
si.cb = sizeof(STARTUPINFO);
GetStartupInfo(&si);
si.hStdError = hWrite;
si.hStdOutput = hWrite;
si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
//关键步骤,CreateProcess函数参数意义请查阅MSDN
if (!CreateProcess(NULL, EXECDOSCMD
,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi))
{
return FALSE;
}
CloseHandle(hWrite);
char buffer[4096] = {0};
DWORD bytesRead;
ofstream ofst;
ofst.open("cmd.txt");
while (true)
{
if (ReadFile(hRead,buffer,4095,&bytesRead,NULL) == NULL)
break;
//buffer中就是执行的结果,可以保存到文本,也可以直接输出
//printf(buffer);
ofst<<buffer;
Sleep(200);
}
ofst.close();
return TRUE;
}
BOOL ExecDosCmd()
{
SECURITY_ATTRIBUTES sa;
HANDLE hRead,hWrite;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
if (!CreatePipe(&hRead,&hWrite,&sa,0))
{
return FALSE;
}
STARTUPINFO si;
PROCESS_INFORMATION pi;
si.cb = sizeof(STARTUPINFO);
GetStartupInfo(&si);
si.hStdError = hWrite;
si.hStdOutput = hWrite;
si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
//关键步骤,CreateProcess函数参数意义请查阅MSDN
if (!CreateProcess(NULL, EXECDOSCMD
,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi))
{
return FALSE;
}
CloseHandle(hWrite);
char buffer[4096] = {0};
DWORD bytesRead;
ofstream ofst;
ofst.open("cmd.txt");
while (true)
{
if (ReadFile(hRead,buffer,4095,&bytesRead,NULL) == NULL)
break;
//buffer中就是执行的结果,可以保存到文本,也可以直接输出
//printf(buffer);
ofst<<buffer;
Sleep(200);
}
ofst.close();
return TRUE;
}