要使用ShellExecuteEx函數(shù)來捕獲標(biāo)準(zhǔn)輸入/輸出/錯誤,你需要使用匿名管道來實現(xiàn)。以下是一個示例代碼:
#include <windows.h>
#include <iostream>
#include <string>
// 函數(shù)用于創(chuàng)建匿名管道
bool CreatePipeHandles(HANDLE& hReadPipe, HANDLE& hWritePipe)
{
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
// 創(chuàng)建管道
if (!CreatePipe(&hReadPipe, &hWritePipe, &saAttr, 0))
{
std::cout << "Failed to create pipe." << std::endl;
return false;
}
// 設(shè)置管道的繼承屬性
if (!SetHandleInformation(hReadPipe, HANDLE_FLAG_INHERIT, 0))
{
std::cout << "Failed to set handle information." << std::endl;
return false;
}
return true;
}
// 函數(shù)用于執(zhí)行Shell命令并捕獲標(biāo)準(zhǔn)輸入/輸出/錯誤
bool ExecuteCommand(const std::string& command, std::string& output)
{
HANDLE hReadPipe, hWritePipe;
// 創(chuàng)建管道
if (!CreatePipeHandles(hReadPipe, hWritePipe))
{
return false;
}
// 創(chuàng)建進(jìn)程信息結(jié)構(gòu)體
STARTUPINFOA si;
ZeroMemory(&si, sizeof(STARTUPINFOA));
si.cb = sizeof(STARTUPINFOA);
si.hStdError = hWritePipe;
si.hStdOutput = hWritePipe;
si.hStdInput = hReadPipe;
si.dwFlags |= STARTF_USESTDHANDLES;
// 創(chuàng)建進(jìn)程信息結(jié)構(gòu)體
PROCESS_INFORMATION pi;
ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
// 啟動Shell命令
if (!CreateProcessA(NULL, const_cast<LPSTR>(command.c_str()), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
{
std::cout << "Failed to execute command." << std::endl;
return false;
}
// 關(guān)閉無用的管道句柄
CloseHandle(hReadPipe);
CloseHandle(hWritePipe);
// 等待進(jìn)程執(zhí)行完成
WaitForSingleObject(pi.hProcess, INFINITE);
// 讀取管道中的輸出數(shù)據(jù)
char buffer[4096];
DWORD bytesRead;
while (ReadFile(si.hStdOutput, buffer, sizeof(buffer) - 1, &bytesRead, NULL) && bytesRead != 0)
{
buffer[bytesRead] = '\0';
output += buffer;
}
// 關(guān)閉進(jìn)程和線程句柄
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return true;
}
int main()
{
std::string command = "dir"; // 你可以修改為你想要執(zhí)行的Shell命令
std::string output;
if (ExecuteCommand(command, output))
{
std::cout << "Command output:" << std::endl;
std::cout << output << std::endl;
}
return 0;
}
在上面的示例代碼中,CreatePipeHandles函數(shù)用于創(chuàng)建匿名管道,ExecuteCommand函數(shù)用于執(zhí)行Shell命令并捕獲標(biāo)準(zhǔn)輸入/輸出/錯誤。你可以將command變量修改為你想要執(zhí)行的Shell命令。執(zhí)行完成后,輸出將被存儲在output字符串中,并打印到控制臺上。