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

标签 c# winforms console-application progress

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

我该怎么做?

最佳答案

可以启动后台进程

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

关于c# - 从 Windows 窗体应用程序 C# 控制控制台应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6760341/

相关文章:

c# - Linq 2 Sql插入没有关系

c# - 正在运行任务的关闭表单

c# - 如何在 datagridview 单元格中选择一行?

c# - 访问 token 验证失败 Microsoft Graph API

multithreading - 线程不是在Delphi的控制台应用程序中终止吗?

c# - 使用 epplus 设置单元格宽度会影响整列

c# - 如何在 C# 中针对流安全地创建 XPathNavigator?

C# 和 CAN 可以在 Game 类之间切换吗?

c# - 分发 clickonce 应用程序的文件

c# - 如何从控制台应用程序调用 REST API?