Console.KeyAvailable() Property in C#


The Console.KeyAvailable() property in C# is used to get a value indicating whether a key press is available in the input stream.

Syntax

The syntax is as follows −

public static bool KeyAvailable { get; }

Example

Let us now see an example to implement the Console.KeyAvailable() property in C# −

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);    } }

Output

This will produce the following output −

Example

Let us now see another example to implement the Console.KeyAvailable() property in C# −

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);    } }

Output

This will produce the following output −

Updated on: 14-Nov-2019

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements