Home > Backend Development > C++ > How Can I Handle Key Presses in C# Console Applications?

How Can I Handle Key Presses in C# Console Applications?

DDD
Release: 2025-01-04 12:57:40
Original
497 people have browsed it

How Can I Handle Key Presses in C# Console Applications?

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);
    }
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template