Home >Backend Development >C++ >How to Handle Console Key Press Events in C#?

How to Handle Console Key Press Events in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-04 01:07:391034browse

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:

  • Console.ReadKey(): Captures the next key pressed by the user without displaying it on the console.
  • The key press is stored in a ConsoleKeyInfo structure, providing access to the key that was pressed.
  • The do-while loop continues reading and displaying key presses until the 'X' key is pressed, which exits the loop.

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!

Statement:
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