Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Console.ReadLine after ReadKey waits for input two times

I don't understand what I am missing here, but it seems that Console.ReadKey() is still active and is causing the Console to make me enter twice when using Console.ReadLine() after invoking Console.ReadKey().

I've searched up and down how to escape ReadKey() once a selection was made, but to no avail.

To clarify, this is the behavior which is unexpected: When the console pops up, the user is presented these three options as an example. When the user then types either "u" or "h", the console does not wait; it immediately performs the action without the user having to press Enter.

Did I do something wrong implementing this?

static void Main(string[] args)
{
    Console.WriteLine("u up");
    Console.WriteLine("h home");
    Console.WriteLine("x exit");
    Console.WriteLine("---------------------------------");
    Console.WriteLine("      [Enter Your Selection]");
    Console.WriteLine("---------------------------------");
    Console.Write("Enter Selection: ");
    ConsoleKeyInfo selection;
    Console.TreatControlCAsInput = true;
    int value;
    selection = Console.ReadKey();
    if (char.IsDigit(selection.KeyChar))
    {
        value = int.Parse(selection.KeyChar.ToString());
        value -= 1;
        Console.WriteLine("You've entered {0}", value);
    }
    else
    {
        switch (selection.Key)
        {
            case ConsoleKey.U:
                blurp();
                break;

            case ConsoleKey.H:
                blurp();
                break;

            case ConsoleKey.X:
                System.Environment.Exit(0);
                break;

            default:
                Console.WriteLine("Invalid Input...");
                break;
        }
    }
}

public static void blurp()
{
    Console.WriteLine("");
    Console.Write("Enter Another Value: ");
    string value = Console.ReadLine();
    Console.WriteLine("You've entered {0}", value);
}
like image 898
Autonomic Avatar asked Feb 20 '17 19:02

Autonomic


1 Answers

I tested with this code and got the same behavior:

Console.Write("Enter Selection: ");
Console.TreatControlCAsInput = true;
ConsoleKeyInfo selection = Console.ReadKey();
if (selection.Key == ConsoleKey.U)
{
    Console.Write("Enter Another Value: ");
    string valueStr = Console.ReadLine();
    Console.WriteLine("You've entered {0}", valueStr);
}

The solution is to not use Console.TreatControlCAsInput = true; as this is causing the problems.

More information is in Stack Overflow question TreatControlCAsInput issue. Is this a bug?.

like image 146
Tatranskymedved Avatar answered Sep 22 '22 00:09

Tatranskymedved