ReadKey while key is not pressed do something
Asked Answered
T

3

5

I am trying to run my code until Esc was pressed. Therefore I am using ReadKey in my Console

var input = Console.ReadKey();
do
{

} while (input.Key != ConsoleKey.Escape);

but at "ConsoleKey" it says that, ConsoleKey isn't possible in 'bool'. How can I fix that? Or what shall I use instead?

Told answered 30/12, 2013 at 19:16 Comment(3)
There is no such error with that code. It'll loop forever, as it stands, but it'll compile just fine. If you read a new key in the body of the loop then it'll even work correctly.Wilonah
hm it gives an error for me... i probably forgot something in the code...Told
The last paragraph of this post was unclear and looked like a completely different question. I've edited the post, feel free to create another question post, OP.Cleaning
P
11

Try this:

ConsoleKeyInfo input;
do
{
    input = Console.ReadKey();
} while (input.Key != ConsoleKey.Escape);
Paquette answered 30/12, 2013 at 19:19 Comment(2)
cut how can i use it like, exiting my program at any point? i'm looking for closing it when ESC is pressed means it has to check all the time. i recently started into programming so i probably dont know how to run multiple threads.Told
So this is very dependent what your requirements are and what for an application you are trying to implement.Villose
G
6

Is there a particular reason you want to use the ESC key instead of the conventional CTRL+C?

You can hook into the Console.CancelKeyPress event for the latter and it is standard in the command-line interface world.

Console.ReadKey() is blocking, which can be problematic in some loops. Let's take this example:

    using System.Threading;
    using System.Threading.Tasks;

    CancellationTokenSource cts;

    public void Run()
    {
        cts = new CancellationTokenSource();
        var task = new Task(DoSomething, cts.Token);

        task.Start();

        while (!task.IsCompleted)
        {
            var keyInput = Console.ReadKey(true);

            if (keyInput.Key == ConsoleKey.Escape)
            {
                Console.WriteLine("Escape was pressed, cancelling...");
                cts.Cancel();
            }
        }

        Console.WriteLine("Done.");
    }

    void DoSomething()
    {
        var count = 0;

        while (!cts.IsCancellationRequested)
        {
            Thread.Sleep(1000);
            count++;

            Console.WriteLine("Background task has ticked ({0}).", count.ToString());
        }
    }

This will do some background work using a Task, while waiting for ESC to be pressed. Cancellation works just fine, however it will be stuck at the Console.ReadKey() one more time after completion (cancellation).

You could use Win32 API such as GetKeyboardState and check the key codes instead, since it is not blocking. However, I recommend using the CancelKeyPress event instead (CTRL+C):

    void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
    {
        Console.WriteLine("Cancelling...");
        cts.Cancel();

        e.Cancel = true;    // Do not terminate immediately!
    }
Grati answered 30/12, 2013 at 21:5 Comment(0)
A
3
ConsoleKeyInfo input;
do
{
    input = Console.ReadKey();
} while (input.Key != ConsoleKey.Escape);

or shorter

while (Console.ReadKey().Key != ConsoleKey.Escape){}
Ashbey answered 30/12, 2013 at 19:19 Comment(2)
but the thing is that it doesnt have to ask at the beginning for closing, but all the time waiting for the user to press ESCTold
@Told because you can't wait for esc and do something in one thread in one timeAshbey

© 2022 - 2024 — McMap. All rights reserved.