如何从 SHELLEXECUTEINFO 对象读取控制台输出?

问题描述

我正在使用 SHELLEXECUTEINFO 对象通过 Visual C++ 执行 C# 控制台应用程序。如何在我的 Visual C++ 应用程序中读取我的 C# 控制台应用程序的控制台输出

这是我目前的工作代码

SHELLEXECUTEINFO ShExecInfo = { 0 };
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = NULL;
ShExecInfo.lpFile = "myapp.exe";        
ShExecInfo.lpParameters = "";
ShExecInfo.lpDirectory = NULL;
ShExecInfo.nShow = SW_HIDE;
ShExecInfo.hInstApp = NULL;
ShellExecuteEx(&ShExecInfo);
WaitForSingleObject(ShExecInfo.hProcess,INFINITE);

解决方法

在使用 ShellExecute/Ex() 时,您无法读取衍生进程的输出。您需要改用 CreateProcess()。它有一个 STARTF_USESTDHANDLES 标志,用于使用您提供的管道重定向衍生进程的 STDIN/STDOUT/STDERR`。有关示例,请参阅 MSDN 上的 Creating a Child Process with Redirected Input and Output