Windows窗体写入控制台

时间:2014-05-14 14:08:03

标签: c# winforms console

我只是试图打开控制台并编写一行并在控制台保持打开后执行它。目前,命令行打开空白而不写任何内容。有什么方法可以解决这个问题吗?

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

cmd.StandardInput.WriteLine("echo hello");
cmd.StandardInput.WriteLine("pause");
cmd.WaitForExit();

3 个答案:

答案 0 :(得分:0)

你很可能只是发出暂停:

cmd.StandardInput.WriteLine("pause");

应该解决它。

请记住添加:

cmd.StartInfo.RedirectStandardInput = false;

如果这不起作用那么很可能仍然是一个问题,正如微软关于CMD专门报告并输出的那样。请参阅:http://connect.microsoft.com/VisualStudio/feedback/details/609801/unable-to-redirect-only-the-standard-input-of-process-cmd-exe-or-batch-file-from-windows-form-application

答案 1 :(得分:0)

这将解决它:

cmd.StartInfo.RedirectStandardOutput = false;

这对我来说非常适合:

using System.Diagnostics;

 namespace ConsoleApplication1
 {
  class Program
  {
    static void Main(string[] args)
    {
        Process cmd = new Process();
        cmd.StartInfo.FileName = "cmd.exe";
        cmd.StartInfo.UseShellExecute = false;
        cmd.StartInfo.RedirectStandardInput = true;
        //cmd.StartInfo.RedirectStandardOutput = true;
        cmd.Start();

        cmd.StandardInput.WriteLine("pause");
        System.Threading.Thread.Sleep(5000);
        cmd.StandardInput.WriteLine(" ");
        cmd.StandardInput.WriteLine("dir /p");
        cmd.StandardInput.WriteLine("exit");
        cmd.WaitForExit();
    }
  }
}

答案 2 :(得分:0)

        Process cmd = new Process();
        cmd.StartInfo.FileName = "cmd.exe";
        cmd.StartInfo.Arguments = "/K \"echo hello\"";
        cmd.Start();