温馨提示×

c# keypress能在控制台应用中使用吗

c#
小樊
85
2024-07-26 17:57:11
栏目: 编程语言

是的,可以在C#控制台应用程序中使用KeyPress事件处理键盘输入。您可以使用Console.ReadKey()方法来读取单个按键的信息,并在按下键时触发事件处理逻辑。以下是一个简单的示例:

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Press any key to continue...");
        
        while (true)
        {
            ConsoleKeyInfo keyInfo = Console.ReadKey();
            
            if (keyInfo.Key == ConsoleKey.Escape)
            {
                Console.WriteLine("Escape key pressed. Exiting program...");
                break;
            }
            
            Console.WriteLine("Key pressed: " + keyInfo.KeyChar);
        }
    }
}

在上面的示例中,我们使用Console.ReadKey()方法读取按键信息,并检查按下的键是否是Escape键。如果是,则退出程序;否则,打印按下的键字符。您可以根据需要扩展此示例以处理其他按键。

0