问题:
有个exe程序,运行后会显示cmd界面,将需要输入两次"K"进行确认。才会全部执行完毕。现需要将其cmd界面及输入过程全部隐藏到后台执行。
解法:通过C#输入输出重定向,并在OutputDataReceived ()中实现输入C的动作来实现,可详见具体代码如下:
private Process _p = null;
...
if (_p == null)
{
_p = new Process();
_p.StartInfo.UseShellExecute = false;
_p.StartInfo.CreateNoWindow = true;
_p.StartInfo.RedirectStandardInput = true;
_p.StartInfo.RedirectStandardOutput = true;
_p.StartInfo.RedirectStandardError = true;
}
Environment.CurrentDirectory = Application.StartupPath;
_p.StartInfo.FileName = Application.StartupPath+ "\\test.exe";
_p.OutputDataReceived += new DataReceivedEventHandler((sender1, e1) =>
{
if (!string.IsNullOrEmpty(e1.Data))
{
string sData= e1.Data;
Debug.WriteLine(sData);
if (sData.IndexOf("output 1") > 1)
{
_p.StandardInput.AutoFlush = true; //写入命令
_p.StandardInput.WriteLine("K");
}
else if (sData.IndexOf("output 2) > 1)
{
_p.StandardInput.AutoFlush = true; //写入命令
_p.StandardInput.WriteLine("K");
}
}
});
_p.ErrorDataReceived += new DataReceivedEventHandler((sender1, e1) =>
{
if (!string.IsNullOrEmpty(e1.Data))
{
Debug.WriteLine( e1.Data);
}
});
_p.Start();
_p.BeginOutputReadLine();
_p.BeginErrorReadLine();
_p.WaitForExit();
_p.Close();
_p = null;