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

1

How can I "read" which key is pressed and set an event for that key if it is pressed. Example: if F1 is pressed Sum, F2 subtracts and so goes I found in the C # help site this example, but I did not 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 only prints tight keys

// 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 the help

    
asked by anonymous 10.05.2016 / 20:13

1 answer

3

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

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 in the console all the keys that you press minus the X key, when the X key is pressed the program will be closed. To check the functional keys just select them through the ConsoleKey enumeration, here are some 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 .

    
10.05.2016 / 21:41