Прочитать на английском

Поделиться через


Console.KeyAvailable Свойство

Определение

Возвращает или задает значение, указывающее, доступно ли нажатие клавиши во входном потоке.

C#
public static bool KeyAvailable { get; }

Значение свойства

Значение true, если нажатие клавиши доступно; в противном случае — значение false.

Исключения

Ошибка ввода/вывода.

Стандартный ввод перенаправляется в файл вместо клавиатуры.

Примеры

В следующем примере показано, как использовать KeyAvailable свойство для создания цикла, который выполняется до нажатия клавиши.

C#
using System;
using System.Threading;

class Sample
{
    public static void Main()
    {
       ConsoleKeyInfo cki;

       do {
           Console.WriteLine("\nPress a key to display; press the 'x' key to quit.");

           // Your code could perform some useful task in the following loop. However,
           // for the sake of this example we'll merely pause for a quarter second.

           while (!Console.KeyAvailable)
               Thread.Sleep(250); // Loop until input is entered.

           cki = Console.ReadKey(true);
           Console.WriteLine("You pressed the '{0}' key.", cki.Key);
        } while(cki.Key != ConsoleKey.X);
    }
}
/*
This example produces results similar to the following:

Press a key to display; press the 'x' key to quit.
You pressed the 'H' key.

Press a key to display; press the 'x' key to quit.
You pressed the 'E' key.

Press a key to display; press the 'x' key to quit.
You pressed the 'PageUp' key.

Press a key to display; press the 'x' key to quit.
You pressed the 'DownArrow' key.

Press a key to display; press the 'x' key to quit.
You pressed the 'X' key.
*/

Комментарии

Значение свойства возвращается немедленно; то есть свойство не блокирует входные данные, KeyAvailable пока не будет доступно нажатие клавиши.

Используйте свойство в сочетании KeyAvailable только с методом ReadKey , а не с методами Read или ReadLine .

Применяется к

Продукт Версии
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1