📜  C#中的Console.KeyAvailable()属性

📅  最后修改于: 2021-05-29 23:11:48             🧑  作者: Mango

Console.KeyAvailable属性用于获取一个值,该值显示输入流中是否有按键可用。除非有按键可用,否则此属性不会阻止输入。

例外情况:

  • InvalidOperationException:如果标准输入重定向到文件而不是键盘。
  • IOException:如果发生I / O错误。

例子:

C#
// C# Program to demonstrate
// KeyAvailable property
using System;
using System.Threading;
 
namespace GFG {
 
class GFG {
 
    public static void Main()
    {
        // declare a new ConsoleKeyInfo object
        ConsoleKeyInfo c = new ConsoleKeyInfo();
 
        // outer loop to work until 'z' is pressed
        do {
            Console.WriteLine("\nPress a key to display; "+
                              "press the 'z' key to quit.");
 
            // inner loop to check whether a key
            // is pressed using KeyAvailable
            while (Console.KeyAvailable == false)
 
                // Loop until input is entered.
                Thread.Sleep(50);
            c = Console.ReadKey(true);
            Console.WriteLine("You pressed the '{0}' key.", c.Key);
 
        } while (c.Key != ConsoleKey.Z);
    }
}
}


输出:

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.console.keyavailable?view=netframework-4.7.2