C#控制台按键事件

时间:2015-02-22 06:49:10

标签: c# console-application keyevent

我刚开始学习c#控制台事件。

c#应用程序是否有可能通过按一个字母自动跳转到新命令。

我在下面有这个迷你代码。

我正在开发一个迷你文本库。

我刚使用了Console.Read(); 所以用户输入字母Y然后他仍然需要按回车键 我想要的是,如果用户按下" y"或键盘中的任何键,语句转到if语句。

是否可能。

        Console.Write("Press Y to start the game.");

        char theKey = (char) Console.Read();


        if (theKey == 'y' || theKey == 'Y')
        {
            Console.Clear();
            Console.Write("Hello");
            Console.ReadKey();
        }
        else
            Console.Write("Error");

1 个答案:

答案 0 :(得分:2)

您应该使用ReadKey方法(msdn):

Console.Write("Press Y to start the game.");

char theKey = Console.ReadKey().KeyChar;

if (theKey == 'y' || theKey == 'Y')
{
    Console.Clear();
    Console.Write("Hello");
    Console.ReadKey();
}
else
    Console.Write("Error");

ReadKey方法的返回值为ConsoleKey枚举,因此您可以在if条件中使用它:

Console.Write("Press Y to start the game.");

ConsoleKey consoleKey = Console.ReadKey().Key;

if (consoleKey == ConsoleKey.Y)
{
    Console.Clear();
    Console.Write("Hello");
    Console.ReadKey();
}
else
    Console.Write("Error");
相关问题