输出重定向时控制台窗口不可见

Rah*_*han 5 .net c# console console-application

我正在使用 .NET 4 控制台应用程序中的以下代码:

private static void AttachToConsole ()
{
    System.Diagnostics.Process process = null;

    process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.RedirectStandardInput = true;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.CreateNoWindow = false;
    process.EnableRaisingEvents = true;
    process.Start();

    process.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived);

    Console.Write("Press any key to continue...");
    Console.ReadKey();

    process.OutputDataReceived -= new DataReceivedEventHandler(Process_OutputDataReceived);
    process.CloseMainWindow();
    process.Close();
}
Run Code Online (Sandbox Code Playgroud)

运行时,仅显示应用程序本身的控制台窗口,但[cmd.exe]进程窗口保持不可见。这是为什么?我该如何改变这种行为?

Joh*_*n L 2

如果你设置了UseShellExecute = truecmd进程窗口就会出现。但是,您需要将 RedirectStandardInput 和 RedirectStandardpOutput 设置为“false”(或将它们注释掉)。

private static void AttachToConsole ()
{
    System.Diagnostics.Process process = null;

    process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    //process.StartInfo.RedirectStandardInput = true;
    //process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.UseShellExecute = true;
    process.StartInfo.CreateNoWindow = false;
    process.EnableRaisingEvents = true;
    process.Start();

    process.OutputDataReceived += null;

    Console.Write("Press any key to continue...");
    Console.ReadKey();

    process.OutputDataReceived -= null;
    process.CloseMainWindow();
    process.Close();
}
Run Code Online (Sandbox Code Playgroud)