0

I am writing a console app and found this method to end a loop on a keypress:

while (!Console.KeyAvailable){//do stuff}

It works, but it echos the key that was pressed back to the prompt. Is there a better method?

edit:

To clarify more, the loop runs and if hit the letter j the loop ends and the program exits. However, I get the following output at the prompt:

C:\>j

Keltari
  • 455
  • 2
  • 5
  • 12

1 Answers1

0

If you want to exit from a loop after a particular key is pressed, then instead of Console.KeyAvailable you can use the Console.ReadKey() function and check the return type of this function as an exit condition.

Here is the implementation.

while (true) {
    var keyPressed = Console.ReadKey(true);
    if (keyPressed.KeyChar == 'j') break;
    //do something
    Console.WriteLine("Key pressed: " + keyPressed.KeyChar);
}

For more details: C# Console - hide the input from console window while typing

karel
  • 5,489
  • 46
  • 45
  • 50
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44