Search code examples
c#keypress

How to get keypress event in console for different keys


I tried googling this but I can't find an answer to this (hope it isn't just my bad searching skills). But what I currently have is this:

static void Main(string[] args)
    {

        while (xa == true)
        {

                switch (switchNum)
                {
                    case 0:
                        Console.WriteLine("Text");
                        break;
                    case 1:
                        Console.WriteLine("Stuff");
                        break;
                    case 2:
                        Console.WriteLine("More Stuff");
                        break;
                }       

        }

And what I want to know is how to change the switchNum when I press a key. Hopefully 3 different keys for each case.

EDIT: Clarification

So currently it will type out of the console like this:

Text
Text
Text
Text
Text
Text

And I want it to change to something else when I press a key e.g. "w"

Text
Text
Text
Text
//Press w here
Stuff
Stuff
Stuff
Stuff
//Pressing another key e.g. q
More Stuff
More Stuff
More Stuff
...

So what I don't know is how to receive different keys, and to keep the loop going (therefore, readkey() might not work).

Thanks in advance!


Solution

  • You need to use Console.ReadKey() to see when a key is press, and as that function is a blocking function you can use Console.KeyAvailable to only call it when you know the user is pressing something. You can read more here and here.

    Your code can be changed to:

    //console input is read as a char, can be used in place of or converted to old switchNum you used
    char input = 'a';//define default so the switch case can use it
    
    while (xa == true)
    {
        //If key is pressed read what it is.
        //Use a while loop to clear extra key presses that may have queued up and only keep the last read
        while (Console.KeyAvailable) input = Console.ReadKey(true).KeyChar;
    
        //the key read has been converted to a char matching that key
        switch (input)
        {
            case 'a':
                Console.WriteLine("Text");
                break;
            case 's':
                Console.WriteLine("Stuff");
                break;
            case 'd':
                Console.WriteLine("More Stuff");
                break;
        }
    }
    

    .

    EDIT: As Jane commented, the loop you're using has no limiter, it will cycle as fast as the CPU running it can go. You should definitely include System.Threading.Thread.Sleep() in the loop to take a rest between each cycle, or wait for a key before printing by converting the while (Console.KeyAvailable) key = Console.ReadKey(true).KeyChar to just key = Console.ReadKey(true).KeyChar