在执行"Console.ReadKey"时允许重定向C#应用程序的StandardInput

Gia*_*971 3 .net c# console redirect input

我有2个申请,A和B.

  • A在流程中调用B.
  • B做一些像Console.WriteLine和Console.ReadLine的东西
  • 感谢这篇MSDN文章,我设法以某种方式重定向B的输出并提供其输入.

  • 我无法做的是在B中使用Console.ReadKey函数.我试了一下这个函数的catch块,我得到了这个错误信息:

当任一应用程序没有控制台或从文件重定向控制台输入时,无法读取密钥.试试Console.Read

事实是,我必须使用Console.ReadKey,所以我需要找到一种方法让它工作......任何想法?

以下是A代码的有用部分


在主要功能:

Process P2 = new Process();
P2.StartInfo.FileName = Environment.CurrentDirectory + "\\Main2.exe";
P2.StartInfo.UseShellExecute = false;
P2.StartInfo.RedirectStandardOutput = true;
P2.OutputDataReceived += new DataReceivedEventHandler(WriteOutput);
P2.StartInfo.RedirectStandardInput = true;
P2.Start();
StreamWriter ExeInput = P2.StandardInput;
P2.BeginOutputReadLine();
ConsoleKeyInfo KeyPressed;
do 
{
    KeyPressed = Console.ReadKey();
    if(KeyPressed.Key == ConsoleKey.Enter)
    {
        Console.WriteLine ();
        ExeInput.Write("\n");
    }
    else
        ExeInput.Write(KeyPressed.KeyChar);
} while (!P2.HasExited);
Run Code Online (Sandbox Code Playgroud)

outputdatareceived的处理程序:

private static void WriteOutput(object sendingProcess, DataReceivedEventArgs outLine)
{
    if (!String.IsNullOrEmpty(outLine.Data))

    {
        Console.WriteLine(outLine.Data);
    }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*ens 5

我不知道ReadKey()在重定向控制台程序的StdIn/StdOut时能够使用的任何方法.此外,为了从子进程读取和写入,您需要确保使用Console.Out.Write()/ Console.In.Read()来防止从子进程抛出异常,因为它缺少控制台窗口.

您可以使用Convert.ToChar(ExeOutput.Read())将输入转换为有效的KeyChar,模仿行为.ReadKey() 还要记住同步和异步读/写.如果您BeginOutputReadLine()以异步方式使用和读取流,则在使用时读取所有输入键之前,P2.HasExited的while条件可能会成立ExeOutput.Read()

        .....
        P2.Start();
        StreamWriter ExeInput = P2.StandardInput;
        StreamReader ExeOutput = P2.StandardOutput;
        do
        {
            var k = P2.StandardOutput.Read();
            var key = Convert.ToChar(k);
            if (key == Convert.ToChar(ConsoleKey.Enter))
            {
                Console.WriteLine();
                ExeInput.Write("\n");
            }
            else
                ExeInput.Write(key);
        } while (!P2.HasExited);
        ....
Run Code Online (Sandbox Code Playgroud)

幸运的是,如果在读取每一行之前进程已经退出,则将缓冲流,因此您可以考虑将条件更改为while(!P2.HasExited && !P2.StandardOutput.EndOfStream)适合您要完成的操作.