Home > front end >  Make user press specific key to progress in program
Make user press specific key to progress in program

Time:03-02

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

CodePudding user response:

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.

  • Related