Приложение консоли управления из приложения Windows формы C # - PullRequest
3 голосов
/ 20 июля 2011

У меня 2 приложения.Один из них - консольное приложение, другой - обычное приложение формы - оба написаны на C #.Я хочу открыть (скрытое от глаз) консольное приложение из окна приложения формы и иметь возможность отправлять командные строки в консольное приложение.

Как я могу это сделать?

Ответы [ 3 ]

5 голосов
/ 20 июля 2011

Вы можете запустить фоновый процесс

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 голос
/ 20 июля 2011

Чтобы запустить консольное приложение, используйте класс System.Diagnostics.Process .

Для отправки команд консольному приложению вам необходимо нечто, называемое межпроцессное взаимодействие.Один из способов сделать это - использовать WCF.Простой учебник можно найти здесь .

1 голос
/ 20 июля 2011

Одним из возможных решений может быть IPC, в частности

NamedPipes

Это уже включено в .NET 4.0.

Привет.

...