Control console application from Windows form application C#

二次信任 提交于 2019-12-30 07:21:03

问题


I have 2 applications. One of them is console application, the other is normal form application - both written in C#. I want to open (hidden from view) the console application form the windows form application and be able to send a command lines to the console application.

How can i do that?


回答1:


You can start the background process

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

and after that use the 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();

If you want to send commands to this process, just use 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:


One of possible solutions can be IPC, in particularly

NamedPipes

That is already wrapped in .NET 4.0.

Regards.




回答3:


To start the console application, use the System.Diagnostics.Process class.

To send commands to the console application you need something that is called Interprocess Communication. One way to do it is by using WCF. A simple tutorial can be found here.



来源:https://stackoverflow.com/questions/6760341/control-console-application-from-windows-form-application-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!