Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Thuộc tính Console.KeyAvailable trong C#

Thuộc tính Console.KeyAvailable trong C# lấy giá trị cho biết xem có phím nào được nhấn trong luồng đầu vào hay không.

Cú pháp

public static bool KeyAvailable { get; }

Ví dụ

using System; 
using System.Threading; 
class Demo { 
    public static void Main (string[] args) { 
        ConsoleKeyInfo cs = new ConsoleKeyInfo(); 
        do { 
            Console.WriteLine("\nNhấn một phím để hiển thị; " + "nhấn phím 'Q' để thoát."); 
            while (Console.KeyAvailable == false) Thread.Sleep(100); 
            cs = Console.ReadKey(true); 
            Console.WriteLine("Bạn đã nhấn phím '{0}'.", cs.Key); 
        } while (cs.Key != ConsoleKey.Q); 
    } 
}

Kết quả

Thuộc tính Console.KeyAvailable trong C#

Ví dụ khác

using System; 
using System.Threading; 
class Demo { 
    public static void Main (string[] args) { 
        ConsoleKeyInfo cs = new ConsoleKeyInfo(); 
        do { 
            Console.WriteLine("\nNhấn một phím để hiển thị; " + "nhấn phím 'P' để thoát."); 
            while (Console.KeyAvailable == false) Thread.Sleep(200); 
            cs = Console.ReadKey(true); 
            Console.WriteLine("Bạn đã nhấn phím '{0}'.", cs.Key); 
        } while (cs.Key != ConsoleKey.Q); 
    } 
}

Kết quả

Thuộc tính Console.KeyAvailable trong C#