In this example, i’ll show you How to make a C# console application terminate on the press of the “Esc” Button.
Example 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Program { static void Main(string[] args) { ConsoleKeyInfo ch; Console.WriteLine("Press the Escape (Esc) key to quit: \n"); do { ch = Console.ReadKey(); // do something with each key press until escape key is pressed } while (ch.Key != ConsoleKey.Escape); } } |
Example 2: Add two numbers in C#. Press the escape key to terminate the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | static void Main(string[] args) { while (true) { Console.Write("Number1 : "); int num1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Number2 : "); int num2 = Convert.ToInt32(Console.ReadLine()); int result = num1 + num2; Console.WriteLine(""); Console.WriteLine("Sum of Two Numbers : " + result); ConsoleKeyInfo ch; Console.WriteLine("Press the Escape (Esc) key to quit: \n"); ch = Console.ReadKey(); if (ch.Key == ConsoleKey.Escape) { Environment.Exit(0); } } } |