Afficher en anglais

Partage via


Console.KeyAvailable Propriété

Définition

Obtient une valeur indiquant si l'appui sur une touche est disponible dans le flux d'entrée.

C#
public static bool KeyAvailable { get; }

Valeur de propriété

true si l'appui sur une touche est disponible, sinon, false.

Exceptions

Une erreur d'E/S s'est produite.

L’entrée standard est redirigée vers un fichier au lieu du clavier.

Exemples

L’exemple suivant montre comment utiliser la KeyAvailable propriété pour créer une boucle qui s’exécute jusqu’à ce qu’une touche soit enfoncée.

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.
*/

Remarques

La valeur de la propriété est retournée immédiatement ; autrement dit, la propriété ne bloque pas l’entrée KeyAvailable tant qu’une pression sur la touche n’est pas disponible.

Utilisez la KeyAvailable propriété conjointement avec la ReadKey méthode uniquement, et non avec les Read méthodes ou ReadLine .

S’applique à

Produit Versions
.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