【问题标题】:Control console application from Windows form application C#来自 Windows 窗体应用程序 C# 的控制台应用程序
【发布时间】:2011-10-09 06:35:47
【问题描述】:

我有 2 个应用程序。 其中一个是控制台应用程序,另一个是普通表单应用程序 - 都是用 C# 编写的。我想从 Windows 窗体应用程序中打开(从视图中隐藏)控制台应用程序,并能够向控制台应用程序发送命令行。

我该怎么做?

【问题讨论】:

    标签: c# winforms console-application progress


    【解决方案1】:

    可以启动后台进程

    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.FileName = "Myapplication.exe";
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    Process process = new Process();
    process.StartInfo = startInfo;
    process.Start();
    

    然后使用Process.StandardOutput property

    // This is the code for the base process
    Process myProcess = new Process();
    // Start a new instance of this program but specify the 'spawned' version.
    ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(args[0], "spawn");
    myProcessStartInfo.UseShellExecute = false;
    myProcessStartInfo.RedirectStandardOutput = true;
    myProcess.StartInfo = myProcessStartInfo;
    myProcess.Start();
    StreamReader myStreamReader = myProcess.StandardOutput;
    // Read the standard output of the spawned process.
    string myString = myStreamReader.ReadLine();
    Console.WriteLine(myString);
    
    myProcess.WaitForExit();
    myProcess.Close();
    

    如果你想向这个进程发送命令,只需使用Process.StandardInput Property

     // Start the Sort.exe process with redirected input.
     // Use the sort command to sort the input text.
     Process myProcess = new Process();
    
     myProcess.StartInfo.FileName = "Sort.exe";
     myProcess.StartInfo.UseShellExecute = false;
     myProcess.StartInfo.RedirectStandardInput = true;
    
     myProcess.Start();
    
     StreamWriter myStreamWriter = myProcess.StandardInput;
    
     // Prompt the user for input text lines to sort. 
     // Write each line to the StandardInput stream of
     // the sort command.
     String inputText;
     int numLines = 0;
     do 
     {
        Console.WriteLine("Enter a line of text (or press the Enter key to stop):");
    
        inputText = Console.ReadLine();
        if (inputText.Length > 0)
        {
           numLines ++;
           myStreamWriter.WriteLine(inputText);
        }
     } while (inputText.Length != 0);
    

    【讨论】:

      【解决方案2】:

      一种可能的解决方案是IPC,尤其是

      NamedPipes

      这已经包含在 .NET 4.0 中。

      问候。

      【讨论】:

        【解决方案3】:

        要启动控制台应用程序,请使用System.Diagnostics.Process class

        要将命令发送到控制台应用程序,您需要一种称为进程间通信的东西。一种方法是使用 WCF。一个简单的教程可以找到here

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-11-19
          相关资源
          最近更新 更多