user7968180
user7968180

Reputation: 155

Pause after first keypress, synchronous solution

There is the whole super simple C# console app here:

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int left = 0;
            Console.SetCursorPosition(++left, 0);
            while (true)
            {
                ConsoleKeyInfo stisknutaKlavesa = Console.ReadKey(true);

                if (stisknutaKlavesa.Key == ConsoleKey.RightArrow)
                {
                    Console.SetCursorPosition(++left, 0);
                    Console.Write("#");
                }
            }
        }
    }
}

Description: When I press RIGHT KEY (and hold it!!) it quickly writes one hash, then there is a pause, and then it fluently keeps writting another hashes further.

How can I get rid of that pause? I have been dealing with identical problem in one of my winform app, but for simplicity I posted it in this console application here.

I have found some answers about this topic but all of them were about javascript (jquery) and i did not understand how to apply it on this my c# project.

And i do not want to resolve it in asynchronous way either. Is there such a solution, please?

enter image description here

Upvotes: 2

Views: 172

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156469

This comes from the way that the windows console (and most other text-based inputs in Windows and other environments) behaves. If you put your cursor on any text input (like your browser's address bar, for instance), and press and hold an arrow key, you will see it move once, pause, and then start moving repeatedly with a much shorter pause.

In effect, your console's ReadKey registers keypresses based on some predefined behaviors of the operating system.

If you want to be able to detect and respond to someone holding a key down, you'll need to use a medium that gives you more low-level access to events like keydown and keyup. Something like Windows Forms, WPF, Unity... pretty much anything that's not Console.

Furthermore, if you want to respond to those key-down and key-up events using timing that's different from how the system treats those events, you'll have to create your own timing mechanism, and only use those events to help you know when things have changed. Examples of this can be found here and here.

If you're trying to make something akin to a video game, you might consider looking into libraries that are specifically designed for these use cases, like Unity3D.

Upvotes: 6

Related Questions