Search code examples
c#.netconsole-applicationlistenerkeypress

Detect key combination being pressed in C# console app


I have a pretty simple console app thats quietly waits for a users to press a key, then performs an action based on the what key was pressed. I had some issues with it, but some helpful users over on this post pointed out where I was going wrong.

The code I currently have to handle a single key press is as follows

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

} while (key != ConsoleKey.Escape);

I'm wondering how I can detect when a combination of 2 or more keys is pressed. I'm not talking about the standard Ctrl + c, but rather something like Ctrl + NumPad1. If a user presses Ctrl + NumPad1, perform action X.

I'm really unsure how to go about doing this, as the current while loop will only loop until a single key is pressed, so wont detect the second key (assuming that its litterally impossible to press two keys at the exact same time.

Is anyone able to provide a steer in the right direction to help achieve this?


Solution

  • If you capture the ConsoleKeyInfo, you will get additional information, including the Modifiers keys. You can query this to see if the Control key was pressed:

    ConsoleKey key;
    
    do
    {
        while (!Console.KeyAvailable)
        {
            // Do something, but don't read key here
        }
    
        // Key is available - read it
        var keyInfo = Console.ReadKey(true);
        key = keyInfo.Key;
    
        if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0)
        {
            Console.Write("Ctrl + ");
        }
        if (key == ConsoleKey.NumPad1)
        {                    
            Console.WriteLine(ConsoleKey.NumPad1.ToString());
        }
        else if (key == ConsoleKey.NumPad2)
        {
            Console.WriteLine(ConsoleKey.NumPad2.ToString());
        }
    
    } while (key != ConsoleKey.Escape);