C # console application: how to prevent the user from holding down a key when using a ReadKey () loop?

advertisements

I'm writing a console app in C#, which reads user input using Console.ReadKey(). It has code that's similar to this:

while(true)
{
    switch(Console.ReadKey(true).Key)
    {
        case ConsoleKey.Enter:
            //code
        case ConsoleKey.UpArrow:
            //code
        case ConsoleKey.DownArrow:
            //code
        case ConsoleKey.Escape:
            //code
    }
}

Now the problem is, if the user holds down any key for more than half a second, Windows registers it as multiple key presses. So if, for the example, the Enter key is held down for a second, the code that goes after case ConsoleKey.Enter: runs about ten times, and I don't want that.

How do I make it so that holding a button down registers as only one key press? Will I have to use Windows Forms for that? (currently my code only relies on the Console class).


If the goal is just to prevent entering keystrokes too fast, something like this might work:

        DateTime lastPressedTime = DateTime.MinValue;
        while (true)
        {
            var key = Console.ReadKey(true).Key;
            if (DateTime.Now > lastPressedTime.AddSeconds(.5))
            {
                switch (key)
                {
                    case ConsoleKey.Enter:
                    //code
                    case ConsoleKey.UpArrow:
                    //code
                    case ConsoleKey.DownArrow:
                    //code
                    case ConsoleKey.Escape:
                    //code
                }
            }
            lastPressedTime = DateTime.Now;
        }

However it will be annoying to the user if they are legitimately typing fast since it will discard anything that comes in quicker than 1/2 second from the last keypress.

If you really want to be sure they aren't just holding down the key too long, you need to monitor for a KeyUp event and only accept another keystroke after you have seen the KeyUp. It is easy using Winforms. It gets a bit more complicated with a Console application.

This question may give more ideas on what it would take to monitor for key state in a Console application: C# arrow key input for a console app