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

时间:2013-06-13 17:27:36

标签: c# .net 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();
}

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

2 个答案:

答案 0 :(得分:2)

如果设置UseShellExecute = true,则会显示cmd进程窗口。您需要将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();
}

答案 1 :(得分:2)

我真的不知道如何修复它,但我知道它为什么会这样。

你设置

UseShellExecute=false;

cmd.exeWindows Command Processor因此,使用Windows shell执行会创建新的控制台窗口,该窗口的输入由cmd.exe处理,输出将定向到终端。

如果设置UseShellExecute=true,窗口会显示,但您将无法重定向输入和输出,这是因为它的工作方式如上所述

编辑: 最重要的部分:你写了“过程窗口”;控制台类型过程根本没有窗口