让用户按特定键以继续程序

发布于 2025-01-10 22:44:23 字数 486 浏览 2 评论 0原文

我目前正在开发一个小型彩票控制台游戏,并想添加一个“工作”机制。我创建了一个新方法,想要添加多个任务,您必须按特定键,例如空格键 > 例如多次。所以像这样(但实际上有效):

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤星 2025-01-17 22:44:23

Console.ReadKey() 方法返回一个 ConsoleKeyInfo 结构,该结构为您提供有关按下哪个键和修饰符所需的所有信息。您可以使用此数据来过滤输入:

void WaitForKey(ConsoleKey key, ConsoleModifiers modifiers = default)
{
    while (true)
    {
        // Get a keypress, do not echo to console
        var keyInfo = Console.ReadKey(true);
        if (keyInfo.Key == key && keyInfo.Modifiers == modifiers)
            return;
    }
}

在您的用例中,您可以这样调用:

WaitForKey(ConsoleKey.SpaceBar);

或者您可以添加专门检查 ConsoleKey.SpaceBarWaitForSpace 方法没有修饰符。

对于更复杂的键盘交互(例如菜单和一般输入处理),您需要功能更强大的东西,但基本概念是相同的:使用Console.ReadKey(true)来获取输入(不显示按下的键),检查结果 ConsoleKeyInfo 记录以确定按下了什么,等等。但是对于等待按下特定键的简单情况,这将起到作用。

The Console.ReadKey() method returns a ConsoleKeyInfo 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:

void WaitForKey(ConsoleKey key, ConsoleModifiers modifiers = default)
{
    while (true)
    {
        // Get a keypress, do not echo to console
        var keyInfo = Console.ReadKey(true);
        if (keyInfo.Key == key && keyInfo.Modifiers == modifiers)
            return;
    }
}

In your use case you'd call that like this:

WaitForKey(ConsoleKey.SpaceBar);

Or you could add a WaitForSpace method that specifically checks for ConsoleKey.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 resultant ConsoleKeyInfo 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文