SilverStitch
SilverStitch

Reputation: 17

Can i make a loop and listen for a key press and get this key value to a variable in C# Console Application without stop the loop

For example this code:

    while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape))
{
     //do something
}

But when the key is pressed instead stop i just get the key value to a variable

Upvotes: 0

Views: 766

Answers (3)

J. Schmale
J. Schmale

Reputation: 486

Here's another sample that might help you.

        ConsoleKeyInfo key = new ConsoleKeyInfo();
        Console.Write("type some characters (ESC to quit)> ");

        while (true)
        {
            key = Console.ReadKey(intercept: true); // use false to allow the characters to display
            
            if(key.Key == ConsoleKey.Escape)
            {
                Console.WriteLine();
                Console.WriteLine("You pressed ESC. The program will terminate when you press the ENTER key.");
                Console.ReadLine();
                return;
            }  
            
            // do some more stuff with the key value from the key press if you want to now
        }

Upvotes: 1

John Wu
John Wu

Reputation: 52240

If you want the loop to continue, take KeyAvailable out of the while condition.

while (true)
{
    if (Console.KeyAvailable) 
    {
        var key = Console.ReadKey(true);
        if (key.Key == ConsoleKey.Escape) break;
    }
    //Do other stuff
}

Upvotes: 1

Joshua Robinson
Joshua Robinson

Reputation: 3539

Console.ReadKey(bool) returns an instance of ConsoleKeyInfo. So, you could store the result of Console.ReadKey(bool) in a variable of type ConsoleKeyInfo and use an inner while loop to wait for a key press.

ConsoleKeyInfo cki;

do
{
   while (!Console.KeyAvailable)
   {
      // Listening for a keypress...
   }

   cki = Console.ReadKey(true);
   // Do something with cki.
} while (cki.Key != ConsoleKey.Escape);

Upvotes: 0

Related Questions