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

我正在制作一个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键作为“跳过”键,它使文本立即出现,但是按下回车键也会创建一个新的文本行,加扰文本。

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

我想你想要的是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文章

您可以使用此类(如此处所示 )监听键输入,而不是仅在Writes之间hibernate:

 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; } } 

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