在当前控制台中运行进程

fer*_*lin 16 c# console process

我正在为Windows编写一个基本shell,我想知道是否有任何方法可以运行subprocess(Process process)以便它使用当前的控制台窗口.我的意思是说我希望重定向输入/输出; 我希望进程从当前控制台获取输入并将输出直接打印到同一控制台窗口.

原因是我希望允许此子进程为输出设置控制台颜色,如果我重定向进程的标准输出,则不会发生这种情况.另外,我目前使用的是代码

while (!process.HasExited)
    process.StandardInput.WriteLine(Console.ReadLine());
Run Code Online (Sandbox Code Playgroud)

将标准输入重定向到流程.然而,如果处理的输入后,立即离开(例如,I型"退出" + 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;
}
Run Code Online (Sandbox Code Playgroud)

Jim*_*hel 21

您需要创建一个ProcessStartInfo并设置UseShellExecutefalse:

var info = new ProcessStartInfo("program.exe", "arguments");
info.UseShellExecute = false;
var proc = Process.Start(info);
proc.WaitForExit();
Run Code Online (Sandbox Code Playgroud)

这将在同一控制台中启动您的程序.

使用上述技术的工作程序:

private static void Main(string[] args)
{
    Console.WriteLine("Starting program");
    var saveColor = Console.BackgroundColor;
    Console.BackgroundColor = ConsoleColor.Blue;
    var info = new ProcessStartInfo("cmd", "/c time");
    info.UseShellExecute = false;
    var proc = Process.Start(info);
    proc.WaitForExit();

    Console.BackgroundColor = saveColor;
    Console.WriteLine("Program exited");
    Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)

当您运行该程序时,它会启动cmd.exe的新副本并运行time命令,该命令要求输入.我只是用cmd.exe作为例子来说明.从标准输入读取的任何程序都可以使用.另请注意,控制台颜色正常工作.