0

I'm making a program for differentiating functions and want to call a specific method as soon as "esc" is pressed.

So far I've tried finding an answer through Google, but I can't seem to find anything that works. Does anyone know if this is possible in a C# console application?

Anders
  • 23
  • 4

1 Answers1

0

There is no event to listen for key presses. Only Console.ReadKey. But you can turn it into a callback using Tasks. Like so:

public static void RegisterKeyHandler(Action<ConsoleKeyInfo> handler)
{
    Task.Run(() =>
    {
        while (true)
        {
            var key = Console.ReadKey();
            handler(key);
        }
    });
}

This only receives keys while the console window is focused.

Rain336
  • 1,450
  • 14
  • 21