0

I need to make it to where my code will only exit the loop when the key that is pressed, is released. I am doing this is console and will need to stay in console.

Here is an example of the code.

ConsoleKeyInfo = ki;

while (true)
{
    ki = Console.ReadKey();

    if (ki.Key == ConsoleKey.A)
    {
        Console.Write("A");
    }
}

As you can see above, when the A key is pressed, it will write A in the console. If you hold down the A key, it will continuously write A.

What I'm wanting is for the console to write A ONCE until the A key is released. Then, if you press A again, it will print again.

I've thought about using "KeyUp" but I'm not able to use it on a console application. But something that would accomplish the following...

ConsoleKeyInfo = ki;

while (true)
{
    ki = Console.ReadKey();

    if (ki.Key == ConsoleKey.A)
    {
        //I know the following isn't actually code, but it's explaining what I want to happen.
        do (onKeyRelease)
        {
            Console.Write("A");
        }
    }
}

Basically, I'm wanting only one thing to happen when the loop when a key is pressed until the key is released. When the key is released, the loop will start again.

Please note that I am using this idea for a Text-Based RPG game. So waiting until another key is pressed (including adding another Console.ReadKey() to the end) would not be ideal.

2 Answers 2

1

1st Suggestion - Have you tried "break" the loop when the console has displayed the "A"?

2nd Suggestion -

ConsoleKeyInfo = ki;
var alreadyPressed = false
while (true)
{
ki = Console.ReadKey();


if (ki.Key == ConsoleKey.A && !alreadyPressed)
{        
        Console.Write("A");
        alreadyPressed = true;        
}}`
Sign up to request clarification or add additional context in comments.

2 Comments

I'm wanting it to loop, though. If I break the loop, I will not be able to input anything else.
Yes, I have. Unfortunately it will do the exact same thing as my original code. Rather than creating a way to edit the loop, I'm wanting to only proceed when the key pressed is released. That way people cannot hold down the key.
0

Store last pressed key and print character only when it is different from the last pressed key.

1 Comment

I'm using this for the controls to a Text-Based RPG game. I need to make it to where I am able to go in the same direction. I'm just trying to prevent the console from trying to catch up with the repeated key.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.