Home >Backend Development >C++ >How to Handle Console Key Press Events in C#?
Console Key Press Event Handling in C#
In console applications, capturing keystrokes requires an approach different from traditional GUI applications. In C#, the following code snippet allows you to register for key press events in a console application:
public class Program { public static void Main() { // Read keystrokes until the 'X' key is pressed ConsoleKeyInfo keyinfo; do { keyinfo = Console.ReadKey(); // Display the pressed key Console.WriteLine(keyinfo.Key + " was pressed"); } while (keyinfo.Key != ConsoleKey.X); } }
Explanation:
Note: For console applications to capture key press events, they require focus. If your application does not have focus, it will not receive key press events.
The above is the detailed content of How to Handle Console Key Press Events in C#?. For more information, please follow other related articles on the PHP Chinese website!