How to Wait for Key Press in C#

Muhammad Maisam Abbas Feb 16, 2024
How to Wait for Key Press in C#

This tutorial will discuss the method to read a keypress in C#.

Wait for Keypress With the Console.ReadKey() Method in C#

The easiest way to wait for a keypress in C# is to use the Console.ReadKey() method. The Console.ReadKey() method in C# reads a keypress in C#. The Console.ReadKey() method halts the program’s execution until a key is pressed. The following code example shows us how to wait for a keypress with the Console.ReadKey() method in C#.

using System;

namespace waitkey {
  static class Program {
    static void Main() {
      Console.WriteLine("Hello, Press any key to progress forward");
      Console.ReadKey();
      Console.WriteLine("This is the End");
    }
  }
}

Output:

Hello, Press any key to progress forward
This is the End

In the above code, we waited for the keypress with the Console.ReadKey() method in C#.

The Console.ReadKey() method can also be used to perform specific operations on specific keys. For example, we can use the Console.ReadKey() method to press Esc key to exit program or the Enter key to continue the program. This example is further illustrated in the coding example below.

using System;

namespace waitkey {
  static class Program {
    static void Main() {
      Console.WriteLine("Hello, Press any key to progress forward");
      Console.ReadKey();
      Console.WriteLine("This is the End");
    }
  }
}

Output#1 (Enter):

Hello, Press Enter to Continue or Esc to Exit Continued Ok

Output#2 (Esc):

Hello, Press Enter to Continue or Esc to Exit

We created a program that gives different outputs on different keypresses with the Console.ReadKey() method in C#.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn