简体   繁体   English

Windows窗体写入控制台

[英]Windows Form Write to Console

I am simply trying to open the console and write a single line and execute it with the console staying open once the line is written. 我只是试图打开控制台并编写一行,并在编写该行后使控制台保持打开状态来执行它。 Currently, the command line is opening blank and not writing anything. 当前,命令行空白为空且未编写任何内容。 Any way to fix this? 有任何解决这个问题的方法吗?

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();

You could most likely just issue a pause: 您很可能只是发出一个暂停:

cmd.StandardInput.WriteLine("pause");

Should solve it. 应该解决它。

Remember to add: 请记住添加:

cmd.StartInfo.RedirectStandardInput = false;

If that does not work then most likely still an issue, as reported at Microsoft regarding CMD specifically and output. 如果这不起作用,则很可能仍然是一个问题,如Microsoft在CMD上专门报道的那样和输出。 See: 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 请参阅: http : //connect.microsoft.com/VisualStudio/feedback/details/609801/unable-to-redirect-only-the-standard-input-of-process-cmd-exe-or-batch-file-from- Windows窗体应用程序

This will fix it: 这将解决它:

cmd.StartInfo.RedirectStandardOutput = false;

This works perfect for me: 这对我来说很完美:

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();
    }
  }
}
        Process cmd = new Process();
        cmd.StartInfo.FileName = "cmd.exe";
        cmd.StartInfo.Arguments = "/K \"echo hello\"";
        cmd.Start();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM