且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#控制台应用程序中使用Keyboard.IsKeyDown

更新时间:2022-05-11 23:08:50

使用

Use Console.ReadKey() to read input from the keyboard in a console application.

请注意,这是一个阻止呼叫.如果您不想阻止,请与Console.KeyAvailable结合使用.例如,该程序将循环并显示每10秒是否按下一个键:

Note that this is a blocking call. If you don't want to block, combine with Console.KeyAvailable. For example, this program will loop and display if a key is pressed every 10th of a second:

static void Main(string[] args)
{
    do
    {
        if (Console.KeyAvailable)
        {
            var key = Console.ReadKey();
            Console.WriteLine(key.Key);
        }
        else
        {
            Console.WriteLine("No key pressed");
        }
        System.Threading.Thread.Sleep(100);
    } while (true);
}