需求: 一个以前的控制台程序,由于命令行方式对用户不够友好,所以加个界面调用控制台程序,但是以前的控制台输出信息就要重定向到新的界面上,要不用户不知道程序信息更不好。
在命令行下重定向本来是很容易的一件事情(Hello >1.txt,Linux 的 | 管道功能更强),但是发现.net里面调用重定向却不是那么容易。
先写一个例子程序,一个Form程序,里面一个Button,每点一次Button,Console.WriteLine一些东西
private void HelloBtn_Click( object sender, EventArgs e)
{
Console.WriteLine(++num);
}
再写另外一个程序调用这个Hello.exe.将Hello.exe的命令行输出定向到TextBox中
private delegate void AppendRichText( string str);
public RedirectForm()
{
InitializeComponent();
}
private void RedirectForm_Load( object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(PrintText));
t.Start();
}
private void PrintText()
{
Process p = new Process();
p.StartInfo = new ProcessStartInfo();
p.StartInfo.FileName = "Hello";
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
StreamReader reader = p.StandardOutput;//截取输出流
string input = reader.ReadLine();//每次读取一行
while (!reader.EndOfStream)
{
//重定向输出到TextBox中
this.Invoke(new AppendRichText(AppendText), input);//WinForm多线程的问题,不能在其他线程改变Form控件属性(除了少数属性)
input = reader.ReadLine();
}
p.WaitForExit();
}
private void AppendText( string text)
{
this.richTextBox1.AppendText(text + " ");
}
这样也可以完成进程之间的一些信息传递。