2

first time posting here, so I apologise in advance in case I miss something important, please let me know if that's the case!

I'm writing a console application that has a menu with several different options in different layers, and I'm trying to make a function that will, at any time as the user works in these menus, notice if the Esc key is pressed. To make my code less cluttered I wrote a separate method that I can simply call at any point when I'm asking for input (like a choice, or entering information into a form, or such). The problem I have is that it always cancels out the first key press. If a user enters a number to move in the menu, the number doesn't get entered, if they enter a name into a form the first letter is missing etc. Is there a way around this?

The code currently looks like this;

public static void checkForEsc()
    {
        ConsoleKeyInfo key = Console.ReadKey(true);

        if (key.Key == ConsoleKey.Escape)
        {
            switch (currentUserisAdmin)
            {
                case true:
                    Menu.AdminMenu();
                    break;

                case false:
                    Menu.CustomerMenu();
                    break;
            }
        }
    }

Thanks in advance :)

Edit:

Might be worth adding that the code where this snippet gets called looks something like this, with very small variations;

Console.WriteLine($"1. Add a user\n2. Remove a user \n3. See user info \n \n9. Cancel");
Program.checkForEsc();
int response2 = CheckIfResponseInt(Console.ReadLine());
Peachy
  • 21
  • 5

1 Answers1

2

You need to write your own line editor instead of using Readline. It's described in the link below. You may need to add support for other control keys such as backspace or add a check that only numeric keys are being pressed.

Listen on ESC while reading Console line

making
  • 408
  • 6
  • 21