- string s = Console.ReadLine();
When a specific key (ex: ESC (ESCAPE)) is pressed, the program below exit.
- using System;
- namespace Test
- {
- class Program
- {
- static void Main(string[] args)
- {
- ConsoleKeyInfo k;
- Console.WriteLine("Press ESC to exit...");
- while (true)
- {
- k = Console.ReadKey(true);
- if (k.Key == ConsoleKey.Escape)
- break;
- Console.WriteLine("{0} --- ", k.Key);
- }
- }
- }
- }
ReadKey and ReadLine functions block input. If you want to do anything until key pressed, you should use KeyAvailable property.
- Console.KeyAvailable
Example
- using System;
- namespace Test
- {
- class Program
- {
- static void Main(string[] args)
- {
- ConsoleKeyInfo k;
- bool bln = true;
- Console.WriteLine("Press ESC to exit...");
- while (true)
- {
- while(!Console.KeyAvailable)
- {
- if(!bln)
- Console.WriteLine("{0:s}", "x");
- bln = true;
- }
- bln = false;
- k = Console.ReadKey(true);
- if (k.Key == ConsoleKey.Escape)
- break;
- Console.Write("{0} --- ", k.Key);
- }
- }
- }
- }