Disabling User Input in a Console Application(在控制台应用程序中禁用用户输入)
问题描述
我正在制作一个基于 C# 控制台文本的游戏,并且因为我希望它看起来更老派,所以我添加了一种效果,使任何文本(描述、教程、对话)看起来都像是正在输入的,并且它看起来像这样:
I am making a C# console text-based game, and because I wanted it to look more old-school, I've added an effect so that any text (descriptions, tutorials, dialogues) looks like it's being typed, and it looks like this:
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 键作为跳过"键,它使文本立即出现,但按 Enter 键也会创建一个新的文本行,打乱文本.
But then I thought that this might be annoying and I thought about adding an option to skip the effect and make all the text appear at once. So I chose the Enter key to be the "skip" key, and it makes the text appear at once, but pressing the enter key also creates a new text line, scrambling the text.
所以我想以某种方式禁用用户输入,以便用户无法在控制台中写入任何内容.有没有办法,例如,禁用命令提示符(命令提示符不是指 cmd.exe,而是闪烁的_"下划线符号)?
So I want to somehow disable user input, so that the user cannot write anything in the console. Is there a way to, for example, disable the command prompt (and by command prompt I don't mean cmd.exe, but the flashing "_" underscore sign)?
推荐答案
我认为你想要的是 Console.ReadKey(true)
它将拦截按下的键并且不会显示它.
I think what you want is Console.ReadKey(true)
which will intercept the pressed key and won't display it.
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 文章
这篇关于在控制台应用程序中禁用用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在控制台应用程序中禁用用户输入
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 使用 rss + c# 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01