如何在应用程序中调用CMD并返回运行结果
要求做一个图形界面的应用程序,输入命令行的命令,在后台调用CMD程序执行该命令但不显示DOS命令行窗口,而且能实时显示运行的结果。哪位知道怎么处理?谢啦
代码语言:javascript复制void CLikeCmdDlg::OnBtnExe()
{
// TODO: Add your control notification handler code here
UpdateData();
CString cs(m_childProcess);
cs = m_cmd;
LPTSTR lpsz = (LPTSTR)(LPCTSTR)cs;
m_editoutput = "";
UpdateData(FALSE);
SECURITY_ATTRIBUTES sa;
HANDLE hRead,hWrite;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
if (!CreatePipe(&hRead,&hWrite,&sa,0))
{
MessageBox("Error on CreatePipe()!");
return;
}
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;
if (!CreateProcess(NULL,/*"c:\windows\system32\cmd.exe /c ping google.com"*/lpsz,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi))
{
MessageBox("Error on CreateProcess()!");
return;
}
CloseHandle(hWrite);
// system("ping google.com");
char buffer[4096];
memset(buffer,0,4096);
DWORD byteRead;
while(true)
{
if (ReadFile(hRead,buffer,4095,&byteRead,NULL) == NULL)
{
break;
}
m_editoutput = buffer;
UpdateData(FALSE);
Sleep(200);
}
}