让用户按特定键以继续程序
我目前正在开发一个小型彩票控制台游戏,并想添加一个“工作”机制。我创建了一个新方法,想要添加多个任务,您必须按特定键,例如空格键 > 例如多次。所以像这样(但实际上有效):
static void Work()
{
Console.WriteLine("Task 1 - Send analysis to boss");
Console.WriteLine("Press the spacebar 3 times");
Console.ReadKey(spacebar);
Console.ReadKey(spacebar);
Console.ReadKey(spacebar);
Console.WriteLine("Task finished - Good job!");
Console.ReadKey();
}
I am currently working on a little lottery console game and wanted to add a "Working" mechanic. I created a new method and want to add multiple tasks where you have to press a specific key like the space bar for example multiple times. So something like this (but actually working):
static void Work()
{
Console.WriteLine("Task 1 - Send analysis to boss");
Console.WriteLine("Press the spacebar 3 times");
Console.ReadKey(spacebar);
Console.ReadKey(spacebar);
Console.ReadKey(spacebar);
Console.WriteLine("Task finished - Good job!");
Console.ReadKey();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Console.ReadKey()
方法返回一个ConsoleKeyInfo
结构,该结构为您提供有关按下哪个键和修饰符所需的所有信息。您可以使用此数据来过滤输入:在您的用例中,您可以这样调用:
或者您可以添加专门检查
ConsoleKey.SpaceBar
的WaitForSpace
方法没有修饰符。对于更复杂的键盘交互(例如菜单和一般输入处理),您需要功能更强大的东西,但基本概念是相同的:使用Console.ReadKey(true)来获取输入(不显示按下的键),检查结果
ConsoleKeyInfo
记录以确定按下了什么,等等。但是对于等待按下特定键的简单情况,这将起到作用。The
Console.ReadKey()
method returns aConsoleKeyInfo
structure which gives you all the information you need on which key and modifiers were pressed. You can use this data to filter the input:In your use case you'd call that like this:
Or you could add a
WaitForSpace
method that specifically checks forConsoleKey.SpaceBar
with no modifiers.For more complex keyboard interactions like menus and general input processing you'll want something a bit more capable, but the basic concept is the same: use
Console.ReadKey(true)
to get input (without displaying the pressed key), check the resultantConsoleKeyInfo
record to determine what was pressed, etc. But for the simple case of waiting for a specific key to be pressed that will do the trick.