相关疑难解决方法(0)

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

我有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)

.net c# console redirect input

3
推荐指数
1
解决办法
5143
查看次数

标签 统计

.net ×1

c# ×1

console ×1

input ×1

redirect ×1