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