C#中控制台输入的奇怪问题

时间:2010-07-03 14:01:23

标签: c# wpf console

当使用Console.Read()时,实现似乎认为只要你按下enter键,就会输入足够的字节来进行永久读取。例如,如果连续两次调用Read,则不能在一行中输入一个值,按Enter键,然后移动到下一行。即使您只输入了一个字符,Read只返回零(编辑:或者一个。我不太确定。)。我也有ReadLine这个问题。我试图在程序终止后保持我的控制台打开输入(我有一个WPF应用程序并手动使用AllocConsole)和/或提示用户输入每个单独的输入。但事实并非如此。如果没有可用的输入,是否有一些按钮要求它阻止?

我写了一个Brainfuck解释器,如果他们不使用输入,Wiki中的示例程序会产生预期的结果。

我想要做的是输入一个字符,按Enter键,将该字符作为字符,重复。

1 个答案:

答案 0 :(得分:1)

在您上次编辑之后,我希望下面的代码可以提供您想要的内容或指向正确的方向。

public static int ReadLastKey()
{
  int lastKey = -1;
  for(;;)
  {
    ConsoleKeyInfo ki = Console.ReadKey();
    if (ki.Key != ConsoleKey.Enter)
    {
      lastKey = (int)ki.KeyChar;          
    }
    else
    {
      return lastKey;
    }
  }       
}

ReadLastKey函数将读取击键并返回按Enter键时按下的最后一个键。

当然,如果你不想记录多次按键,你可以删除循环并只使用Console.ReadKey两次,一次按键,然后第二次等待回车键。或者其中一种的一些排列。

这是一个简单版本的功能,只允许按一次键,然后等待按下回车键。请注意,这非常简单,您可能希望处理其他退出条件等。

public static int ReadLastKey()
{
  int lastKey = -1;
  ConsoleKeyInfo ki;

  // Read initial key press
  ki = Console.ReadKey();

  // If it is enter then return -1
  if (ki.Key == ConsoleKey.Enter) return lastKey;

  lastKey = (int)ki.KeyChar;

  // Wait for the user to press enter before returning the last key presss,
  // and do not display key the errant key presses.
  do
  {
    ki = Console.ReadKey(true);
  } while (ki.Key != ConsoleKey.Enter);

  return lastKey;      
}