当你需要调用命令行程序,并获取它的命令行输出内容的时候,这个函数就可以满足你的需要。
String ExecDosCmd(String cmd, TMemo *memo)
{
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, cmd.c_str(), NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi))
{
return FALSE;
}
CloseHandle(hWrite);
char buffer[4096] = {0};
DWORD bytesRead;