Handling Key Press Events in C# Console Applications
In C# console applications, detecting key presses requires a slightly different approach compared to other GUI-based applications. To achieve this, we can leverage the ConsoleKeyInfo object.
Solution with Focus Management
If your console application is the active and focused window, you can use the following code:
public class Program { public static void Main() { ConsoleKeyInfo keyInfo; do { keyInfo = Console.ReadKey(); Console.WriteLine($"{keyInfo.Key} was pressed"); } while (keyInfo.Key != ConsoleKey.X); } }
This code declares a ConsoleKeyInfo variable keyInfo and enters a loop. In the loop, Console.ReadKey() reads and displays the pressed key on the console screen. The loop continues until the 'x' key is pressed, which acts as the exit condition.
System-Wide Key Press Events with Windows Hooks
If you want to gather system-wide key press events (i.e., regardless of which application has focus), you can use Windows hooks. For example, you can use the SetWindowsHookEx function to create a keyboard hook. However, this approach requires more complex low-level programming and is beyond the scope of this discussion.
The above is the detailed content of How Can I Handle Key Presses in C# Console Applications?. For more information, please follow other related articles on the PHP Chinese website!