我需要为我的C#进程获取一个输入命令。
我的C#代码适用于测试批处理文件,而不适用于fortran控制台应用程序
我读过这篇文章:C# Process Call, Interact with Standard Input and Standard Output
但它对我不起作用。
任何人都可以给我一些提示吗?
我的样本批处理文件(test.bat):
注意:此批处理文件模拟我的另一个应用程序。
@echo off
cls
dir
echo "please input enter key"
pause
tree
我的C#代码:
private Process _process = null;
private bool _bEnterCR = false;
private void Begin_Click(object sender, RoutedEventArgs e)
{
this.tbOutput.Text = "";
_bEnterCR = false;
if (null != _process)
{
_process.Dispose();
}
string strPathName = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
// Use ProcessStartInfo class
_process = new Process();
_process.StartInfo.CreateNoWindow = true;
_process.StartInfo.UseShellExecute = false;
_process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
_process.StartInfo.FileName = strPathName + "\\test.bat";
_process.StartInfo.WorkingDirectory = strPathName + "\\Output\\";
_process.StartInfo.RedirectStandardError = true;
_process.StartInfo.RedirectStandardInput = true;
_process.StartInfo.RedirectStandardOutput = true;
//_process.EnableRaisingEvents = true;
_process.OutputDataReceived += new DataReceivedEventHandler(OnOutputDataReceived);
_process.ErrorDataReceived += new DataReceivedEventHandler(OnOutputDataReceived);
//_process.Exited += new EventHandler(OnProcessExited);
_process.Start();
_process.BeginOutputReadLine();
_process.BeginErrorReadLine();
}
private void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (String.IsNullOrEmpty(e.Data) == false)
{
if (e.Data.Contains("please input enter key") && _bEnterCR == false)
{
Debug.WriteLine("Pause Found, Entering <CR> command");
// work for batch file, not for console application
_process.StandardInput.Write(@"\r\n");
_bEnterCR = true;
}
new Thread(() =>
{
this.Dispatcher.Invoke(new Action(() =>
{
tbOutput.AppendText(e.Data + Environment.NewLine);
}));
}).Start();
}
}