C# Console - Press Any Key to Exit

If your console program is closing immediately before you see anything then add this code to your program. It doesn't consume any system resources. When you enter something, program will exit.

  1. string s = Console.ReadLine();

When a specific key  (ex: ESC (ESCAPE)) is pressed, the program below exit.
  1. using System;
  2.  
  3. namespace Test
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             ConsoleKeyInfo k;
  10.  
  11.             Console.WriteLine("Press ESC to exit...");
  12.             while (true)
  13.             {
  14.                 k = Console.ReadKey(true);
  15.                 if (k.Key == ConsoleKey.Escape)
  16.                     break;
  17.  
  18.                 Console.WriteLine("{0} --- ", k.Key);
  19.             }
  20.         }
  21.     }
  22. }

ReadKey and ReadLine functions block input. If you want to do anything until key pressed, you should use KeyAvailable property.
  1. Console.KeyAvailable

Example
  1. using System;
  2.  
  3. namespace Test
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             ConsoleKeyInfo k;
  10.             bool bln = true;
  11.  
  12.             Console.WriteLine("Press ESC to exit...");
  13.             while (true)
  14.             {                
  15.                 while(!Console.KeyAvailable)
  16.                 {
  17.                     if(!bln)
  18.                         Console.WriteLine("{0:s}", "x");
  19.                     bln = true;
  20.                 }
  21.                 bln = false;
  22.  
  23.                 k = Console.ReadKey(true);
  24.                 if (k.Key == ConsoleKey.Escape)
  25.                     break;
  26.  
  27.                 Console.Write("{0} --- ", k.Key);
  28.             }
  29.         }
  30.     }
  31. }
m ant / Mechanical Ant