用C#从Windows窗体应用程序控制控制台应用程序

3

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

我该如何做到这一点?

3个回答

7
您可以启动后台进程。
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "Myapplication.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();

接着使用Process.StandardOutput属性

// 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属性
 // 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);

1

其中一种可能的解决方案可以是IPC,特别是

命名管道

它已经包装在.NET 4.0中。

敬礼。


1

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接