0

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();
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
cloudified
  • 13
  • 5
  • 3
    Read up on the [`Console.ReadKey()` documentation](https://learn.microsoft.com/en-us/dotnet/api/system.console.readkey?view=net-6.0) – Jesse Mar 01 '22 at 22:42
  • 2
    check the return value of readkey. If it's not what you expect, repeat in a loop. Encapsulate this logic into your own small function. – Pac0 Mar 01 '22 at 22:42
  • Does this answer your question? [How to read a key pressed by the user and display it on the console?](https://stackoverflow.com/questions/3068168/how-to-read-a-key-pressed-by-the-user-and-display-it-on-the-console) – Heretic Monkey Mar 01 '22 at 23:14
  • See also [How to handle key press event in console application](https://stackoverflow.com/q/8898182/215552) – Heretic Monkey Mar 01 '22 at 23:17

1 Answers1

0

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.

Corey
  • 15,524
  • 2
  • 35
  • 68