2011-07-20 264 views
3

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

我该怎么做?

回答

5

可以启动后台进程

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

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

NamedPipes

这已经包装在.NET 4.0中。

问候。

1

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

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

相关问题