Reputation: 17
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
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
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
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