Infernal
Infernal

Reputation: 45

Wait for specific key to exit without interrupting other code

[This is not a duplicate as my problem is different; I don't want to close my program and I don't want to use Console.ReadKey() in the main code!]

I'd like to exit the current menu of my program (NOT end it!) if the user pressed e.g. "Escape" but I don't want to do it with Console.ReadKey in the code body.

I'll present you my code first:

while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape))
{
string input = Console.ReadLine();
// if(input == // ... and so on
// rest of code
}

That's the idea I had. The problem though is that pressing Escape won't kick me out of the while-loop because of the ReadLine. I want to leave the loop WHENEVER I press a specific key. May it be while Console.ReadLine() is active or something else, it doesn't matter.

Is there a simple way to do that?

Upvotes: 0

Views: 606

Answers (1)

EZI
EZI

Reputation: 15364

You can write your own ReadLine.

This code will return null if ESC is pressed, otherwise the string user entered..

static string ReadLine()
{
    StringBuilder sb = new StringBuilder();
    while(true)
    {
        var keyInfo = Console.ReadKey(true);

        if (keyInfo.Key == ConsoleKey.Escape) return null;
        if (keyInfo.Key == ConsoleKey.Enter)
        {
            Console.WriteLine();
            return sb.ToString();
        }
        if (keyInfo.Key == ConsoleKey.Backspace && sb.Length > 0)
        {
            Console.Write(keyInfo.KeyChar + " " + keyInfo.KeyChar);
            sb.Length--;
            continue;
        }
        if (Char.IsControl(keyInfo.KeyChar)) continue;

        Console.Write(keyInfo.KeyChar);
        sb.Append(keyInfo.KeyChar);
    }
}

Upvotes: 1

Related Questions