How can I detect if a nondirectional key has been pressed in a console application using an optional parameter in a method?

61 views Asked by At

I have been tasked with adding an optional parameter to a method in a console app I am developing that can detect if any other key, other than the arrow keys on my pc number pad, has been pressed while my app is running. I have tried for hours searching for a solution to this problem on the web have come up empty thus far. The code I am attempting to modify is as follows:

void Move()
{
    int lastX = playerX;
    int lastY = playerY;

        switch (Console.ReadKey(true).Key)
        {
        case ConsoleKey.UpArrow:
            playerY--;
            break;
        case ConsoleKey.DownArrow:
            playerY++;
            break;
        case ConsoleKey.LeftArrow:
            playerX--;
            break;
        case ConsoleKey.RightArrow:
            playerX++;
            break;
        case ConsoleKey.Escape:
            shouldExit = true;
            break;
    }

I need to add an optional parameter to the Move() method above and then call this method elsewhere in my app so that my application will stop running when any key but the arrow keys on the numpad of my pc are pressed. Sorry for the extremely long sentence. Any tips/advice appreciated.

All I've done so far is web research on how to write an optional parameter that can detect nondirectional key input in a running console app. I have not found any answers as of yet.

1

There are 1 answers

0
Vector On

Have a look at this

ConsoleKey key;

do { while (!Console.KeyAvailable) { // Do something, but don't read key here }

// Key is available - read it
key = Console.ReadKey(true).Key;

if (key == ConsoleKey.NumPad1)
{
    Console.WriteLine(ConsoleKey.NumPad1.ToString());
}
else if (key == ConsoleKey.NumPad2)
{
    Console.WriteLine(ConsoleKey.NumPad1.ToString());
}

} while (key != ConsoleKey.Escape);