在控制台应用程序中禁用用户输入

Disabling User Input in a Console Application

我正在制作一款基于 C# 控制台文本的游戏,因为我希望它看起来更老派,所以我添加了一种效果,使任何文本(描述、教程、对话)看起来都像是在键入,它看起来像这样:

public static int pauseTime = 50;

class Writer
{
    public void WriteLine(string myText)
    {
        int pauseTime = MainClass.time;
        for (int i = 0; i < myText.Length; i++)
        {
                Console.Write(myText[i]);
                System.Threading.Thread.Sleep(pauseTime);
        }
        Console.WriteLine("");
    }
}

但后来我觉得这可能很烦人,我考虑添加一个选项来跳过效果并让所有文本同时出现。所以我选择 Enter 键作为 "skip" 键,它使文本立即出现,但按下 enter 键也会创建一个新的文本行,打乱文本。

所以我想以某种方式禁用用户输入,以便用户无法在控制台中写入任何内容。有没有办法,例如,禁用命令提示符(命令提示符我不是指 cmd.exe,而是闪烁的“_”下划线符号)?

您可以使用此 class(如 suggested here)监听按键输入,而不仅仅是在写入之间休眠:

class Reader {
  private static Thread inputThread;
  private static AutoResetEvent getInput, gotInput;
  private static ConsoleKeyInfo input;

  static Reader() {
    getInput = new AutoResetEvent(false);
    gotInput = new AutoResetEvent(false);
    inputThread = new Thread(reader);
    inputThread.IsBackground = true;
    inputThread.Start();
  }

  private static void reader() {
    while (true) {
      getInput.WaitOne();
      input = Console.ReadKey();
      gotInput.Set();
    }
  }

  public static ConsoleKeyInfo ReadKey(int timeOutMillisecs) {
    getInput.Set();
    bool success = gotInput.WaitOne(timeOutMillisecs);
    if (success)
      return input;
    else
      return null;
  }
}

在你的循环中:

Console.Write(myText[i]);
if (pauseTime > 0)
{
    var key = Reader.ReadKey(pauseTime);
    if (key != null && key.Key == ConsoleKey.Enter)
    {
        pauseTime = 0;
    }
}

我只是手写了这个,没有检查过,所以如果它不起作用请告诉我

我想你想要的是Console.ReadKey(true),它将拦截按下的键并且不会显示它。

class Writer
{
    public void WriteLine(string myText)
    {
        for (int i = 0; i < myText.Length; i++)
        {
            if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Enter)
            {
                Console.Write(myText.Substring(i, myText.Length - i));
                break;
            }
            Console.Write(myText[i]);
            System.Threading.Thread.Sleep(pauseTime);
        }
        Console.WriteLine("");
    }
}

来源:MSDN Article