每一种技术都有其诱人之处。
分类: C/C++
2011-10-19 23:59:06
AnsiString __fastcall TMainForm::RunShell (AnsiString sCommand){
SECURITY_ATTRIBUTES sa = {0};
sa.lpSecurityDescriptor = NULL; // 使用系统默认的安全描述符
sa.bInheritHandle = TRUE; // 是否继承句柄
HANDLE hRead, hWrite; // 指向读写端句柄的指针
if (!CreatePipe (&hRead, &hWrite, &sa, 0))
return Exception (); // 创建管道
STARTUPINFO si = {0};
GetStartupInfo(&si);
si.hStdError = hWrite; // 重定向错误管道
si.hStdOutput = hWrite; // 重定向输出管道
si.wShowWindow = SW_HIDE; // 隐藏 CMD 窗口
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
PROCESS_INFORMATION pi = {0};
if (!CreateProcess (NULL, sCommand.c_str () ,NULL, NULL, TRUE,
NULL, NULL, NULL, &si, &pi))return Exception(); // 创建进程
CloseHandle (hWrite); // 关闭句柄
CHAR szReadBuf[1024]; // 创建缓冲区
DWORD dwByteRead = 0; // 字符串读取游标
AnsiString Data;
while (ReadFile (hRead, szReadBuf, sizeof (szReadBuf) - 1, &dwByteRead, NULL)){
szReadBuf[dwByteRead] = '\0'; // 填充末尾
Data += (AnsiString)szReadBuf; // 连接字符串
}
CloseHandle(hRead); // 关闭句柄
return Data;
}