我正在为Windows编写一个基本的shell,我想知道是否有办法运行一个子进程(Process process
) 以便它使用当前控制台窗口。我的意思是我不想重定向输入/输出;我希望该进程从当前控制台获取输入并直接将输出打印到同一控制台窗口。
原因是我希望允许此子进程设置输出的控制台颜色,如果我重定向了进程的标准输出,这是不可能发生的。另外,我目前使用以下代码:
while (!process.HasExited)
process.StandardInput.WriteLine(Console.ReadLine());
将标准输入重定向到进程。然而,如果进程在接收到输入后立即退出(例如,我输入“exit”+ ENTER,进程退出),此循环将再次运行,因此控制台正在等待用户的输入,但该进程不会使用它(它即将退出)。
所以,简单地说,我如何在当前控制台中运行进程,使其可以设置控制台颜色并直接从控制台获取输入?
编辑:下面是我的代码中与此问题相关的方法:
static int runExe(string exePath, params string[] args)
{
ProcessStartInfo startInfo = new ProcessStartInfo(exePath, args)
{
ErrorDialog = false,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true
};
Process process = new Process() { StartInfo = startInfo };
process.Start();
ReadThreadState stdout = readThread(process.StandardOutput, false);
ReadThreadState stderr = readThread(process.StandardError, true);
while (!process.HasExited)
process.StandardInput.WriteLine(Console.ReadLine());
stdout.stop = stderr.stop = true;
return process.ExitCode;
}
class ReadThreadState
{
public bool stop;
}
private static ReadThreadState readThread(StreamReader reader, bool isError)
{
ReadThreadState state = new ReadThreadState();
new Thread(() =>
{
while (!state.stop)
{
int current;
while ((current = reader.Read()) >= 0)
if (isError)
writeError(((char)current).ToString(), ConsoleColor.Red);
else
Console.Write((char)current);
}
}).Start();
return state;
}
cmd.exe
的/c
选项进行实验。例如Process.Start("cmd.exe", "YOURAPP.exe /c");
。 - Anricmd.exe
运行它。 - feralin