C# 中的 Console.KeyAvailable() 属性

csharpserver side programmingprogramming更新于 2025/10/8 13:12:00

C# 中的 Console.KeyAvailable() 属性用于获取一个值,该值指示输入流中是否有按键可用。

语法

语法如下 −

public static bool KeyAvailable { get; }

示例

现在让我们看一个在 C# 中实现 Console.KeyAvailable() 属性的示例 −

using System;
using System.Threading;
class Demo {
   public static void Main (string[] args) {
      ConsoleKeyInfo cs = new ConsoleKeyInfo();
      do {
         Console.WriteLine("
Press a key to display; "+ "press the 'Q' key to quit.");          while (Console.KeyAvailable == false)Thread.Sleep(100);          cs = Console.ReadKey(true);          Console.WriteLine("You pressed the '{0}' key.", cs.Key);       }        while (cs.Key != ConsoleKey.Q);    } }

输出

这将产生以下输出 −

示例

现在让我们看另一个在 C# 中实现 Console.KeyAvailable() 属性的示例 −

using System;
using System.Threading;
class Demo {
   public static void Main (string[] args) {
      ConsoleKeyInfo cs = new ConsoleKeyInfo();
      do {
         Console.WriteLine("
Press a key to display; "+ "press the 'P' key to quit.");          while (Console.KeyAvailable == false)Thread.Sleep(200);          cs = Console.ReadKey(true);          Console.WriteLine("You pressed the '{0}' key.", cs.Key)       }       while (cs.Key != ConsoleKey.Q);    } }

输出

这将产生以下输出 −


相关文章