We frequently read data from user input in our C# application. However, we sometimes need to detect a key press and continue the operation. In this article, we discuss how to detect if a key is pressed in a C# console application. By understanding the usage of these features, we can create interactive and responsive console applications ensuring an intuitive and better user experience.

To download the source code for this article, you can visit our GitHub repository.

Let’s dive in.

Usage of Console.ReadKey

Console.ReadKey() is a basic method for detecting key presses in C# console applications. It waits for the user to press a key and then returns information about the key pressed. For simple input scenarios, like navigating a menu or pausing execution until the user signals readiness to proceed, this method is quite useful. However, given its blocking nature, the application cannot perform other tasks while waiting for input.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

Sometimes, we need to detect a key press, but we do not want to stop the process while waiting for a key press. For instance, if we use the Console.ReadKey() method, the entire process gets halted, until a key is pressed. This is not useful when waiting for a key press without stopping the entire process.

For example, if we want to run a counter, and let’s say that the counter continues to increment until the ‘Esc’ key is pressed, Console.ReadKey() would not help as it will stop the counter increment until a key is pressed.

Let’s check out this issue while using Console.ReadKey():

public void ReadKeyUse()
{
    for (int i = 0; i < 2; i++)
    {
        Console.WriteLine("Press any key to continue...");
        var keyInfo = Console.ReadKey();
        Console.WriteLine("\nYou pressed: " + keyInfo.Key);
    }

    Console.WriteLine("Process stopped");
    Console.ReadKey();
}

Here, we create a loop that stops for user input every time the process reaches Console.ReadKey().

We use the ReadKey() method to hold the process from proceeding further until we press some key. Thus failing the objective of continuing the process while waiting for a key press:

Press any key to continue...
w
You pressed: W
Press any key to continue...
d
You pressed: D
Process stopped

Here, as we can see, the process pauses until someone presses a key. Therefore, if we want to keep the process running while waiting for the key press, this scenario wouldn’t be possible.

Utilizing Console.KeyAvailable to Detect if a Key is Pressed in C#

Console.KeyAvailable is a bool property of the Console class that returns true when a key is pressed. This property checks if a key press is available in the input buffer without pausing execution. Developers can use this feature to poll for key presses in a loop, allowing the application to handle other tasks simultaneously. We can use this in conjunction with the Console.ReadKey() method.

Let’s use a do-while loop to keep the program running, executing instructions until pressing the ‘x’ key:

public void KeyAvailableUse()
{
    do
    {
        Console.WriteLine("Press 'x' to stop!");
        Thread.Sleep(10);
        Console.Clear();
    } while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.X));

    Console.WriteLine("Process stopped");
}

Here, we check the Console.KeyAvailable property is true and if the key pressed is the ‘x’ key, this indicates a key press has occurred. 

Once both conditions are true, the do-while loop breaks, or in other words, the process terminates.

Conclusion

In C# console applications, when we want to determine key presses, we utilize the Console.KeyAvailable bool property in conjunction with Console.ReadKey(). This lets us create applications that run continuously until we press a key. This helps us create better console applications that give users a rich and interactive user experience.

By expanding our knowledge of key press detection and application in C# console applications, we can now create more dynamic, efficient, and user-friendly applications.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!