C#如何获得另一个控制台应用程序的输出

控制台应用程序是C++写的,主体是一个while的死循环,每接收一行输入就会有一行输出,接收特定的命令后退出。( 比如 while(1) { scanf("%d%d",&a,&b);if(a==0&&b==0) break;else printf("%d\n",a+b); } //实例中当然不会这么简单,只是该程序已经写死,无法修改了),然后我就在C#里面用一个Process类对象,重定义该控制台应用程序的输入输出,但是实践中发现控制台应用程序在退出前是无法获得其标准化输出的,就是说还在while循环体里面的话,在C#程序里面调试的时候会卡在读取的那行代码。我现在想在C#程序里面操控这个控制台应用程序的输入输出,每发送一行命令即获得该命令的执行结果而不要等控制台应用程序退出,请问该如何实现?
我把我测试的代码贴出来,大家帮我看看哪里应该修改(C#部分)。
C++代码
#include <stdio.h>
void main()
{
int a,b;
while(1)
{
scanf("%d%d",&a,&b);
if(a==0&&b==0) return;
printf("%d+%d=%d\n",a,b,a+b);
}
}

C#代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace Test
{
class Program
{
static void Main(string[] args)
{
string result;
Process p = new Process();
p.StartInfo.FileName = @"C:\\a.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.Start();
p.StandardInput.WriteLine("1 2");
p.StandardInput.Flush();
result = p.StandardOutput.ReadLine();
Console.WriteLine(result);
Console.ReadKey();
}
}
}

第1个回答  2012-05-02
这个得用钩子函数,具体实现我就不说了。我也很懒的。
相似回答