How to know which keys are pressed in C# Consoleapp and set events

Asked

Viewed 1,012 times

1

How can I "read" which key is pressed and set an event for such a key if pressed. Example: if you press F1 Sum, F2 subtracts and so on I found this example on the C# help site, but I didn’t understand how it works:

    using System;

class Example 
{
   public static void Main() 
   {
      ConsoleKeyInfo cki;
      // Prevent example from ending if CTL+C is pressed.
      Console.TreatControlCAsInput = true;

      Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.");
      Console.WriteLine("Press the Escape (Esc) key to quit: \n");
      do {
         cki = Console.ReadKey(true);
         Console.Write("You pressed ");
         if ((cki.Modifiers & ConsoleModifiers.Alt) != 0) Console.Write("ALT+");
         if ((cki.Modifiers & ConsoleModifiers.Shift) != 0) Console.Write("SHIFT+");
         if ((cki.Modifiers & ConsoleModifiers.Control) != 0) Console.Write("CTL+");
         Console.WriteLine("{0} (character '{1}')", cki.Key, cki.KeyChar);
      } while (cki.Key != ConsoleKey.Escape);
   }
}

But this code just prints the keystrokes pressed

// This example displays output similar to the following:
//       Press any combination of CTL, ALT, and SHIFT, and a console key.
//       Press the Escape (Esc) key to quit:
//       
//       You pressed CTL+A (character '☺')
//       You pressed C (character 'c')
//       You pressed CTL+C (character '♥')
//       You pressed K (character 'k')
//       You pressed ALT+I (character 'i')
//       You pressed ALT+U (character 'u')
//       You pressed ALT+SHIFT+H (character 'H')
//       You pressed Escape (character '←')

Thanks for your help

  • Try this: Console.Readkey(true). Key == Consolekey.F1; //this will compare whether the character typed equals F1

  • That worked.

1 answer

3

Basically you can use the class ConsoleKeyInfo to get the keys pressed, see below an example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExemploKey
{
    class Program
    {
        static void Main(string[] args)
        {
            ConsoleKeyInfo key;

            do
            {
                key = Console.ReadKey();
                Console.WriteLine(key.Key + " foi pressionada.");

            } while (key.Key != ConsoleKey.X);
        }
    }
}

In this case the application will display on the console all keys you press except the key X, when the key X is pressed the program will be terminated. To check the functional keys just select them through the enumeration ConsoleKey, see a few more examples:

ConsoleKey.F1;
ConsoleKey.F10;
ConsoleKey.F13;

This enum has all the keys that will be used by you.

Sources:
Consolekeyinfo.
Consolekey.
how to Handle key press Event in console application.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.