有时候为了更好的监控程序,不用BAT文件执行程序而是用WIN32程序。那么在VC中,怎么调用CMD命令行,并且读取CMD控制台的内容呢,其实很简单。一个线程搞定!
/************************************************************************/
/* 线程函数 */
/************************************************************************/
DWORD WINAPI CWeChatDlg::ThreadFun(LPVOID lpParam)
{
CWeChatDlg* dlg = (CWeChatDlg*)lpParam;
dlg->m_Exit = true;
SECURITY_ATTRIBUTES sa;
HANDLE hRead,hWrite;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL; //使用系统默认的安全描述符
sa.bInheritHandle = TRUE; //创建的进程继承句柄
if (!CreatePipe(&hRead,&hWrite,&sa,0)) //创建匿名管道
{
::MessageBox(NULL,"CreatePipe Failed!","提示",MB_OK | MB_ICONWARNING);
return 0;
}
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si,sizeof(STARTUPINFO));
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,"java -jar WeChatRobot.jar",NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi)) //创建子进程
{
::MessageBox(NULL,"CreateProcess Failed!","提示",MB_OK | MB_ICONWARNING);
return 0;
}
CloseHandle(hWrite); //关闭管道句柄
char buffer[4096] = {0};
DWORD bytesRead;
dlg->m_Pid = pi.dwProcessId;
while (dlg->m_Exit)
{
memset(buffer,0,sizeof(buffer));
if (ReadFile(hRead,buffer,4095,&bytesRead,NULL))
{
dlg->m_Text += buffer;
//显示输出信息到编辑框,并刷新窗口
int len = dlg->m_Text.length();
dlg->m_Edit.SetWindowText(dlg->m_Text.c_str());
dlg->m_Edit.SetSel(len, len);
dlg->m_Edit.LineScroll(dlg->m_Edit.GetLineCount());
}
Sleep(100);
}
CloseHandle(hRead);
return 1;
}
完整工程在附件列表中下载!
本文链接:https://it72.com:4443/12271.htm