C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
ReadKey: This returns once a key is pressed. We call instance properties on the ConsoleKeyInfo to determine the input.
ConsoleKeyInfo: This is a struct (it is immutable). ReadKey() returns a new ConsoleKeyInfo instance on each call.
StructKey: When you call the Key property accessor on the ConsoleKeyInfo, you are reading the values that were already set in the struct.
Modifiers: The Modifiers property returns a value of type ConsoleModifiers, which is an enumerated constant.
PropertyC# program that uses Console.ReadKey
using System;
class Program
{
static void Main()
{
Console.WriteLine("... Press escape, a, then control X");
// Call ReadKey method and store result in local variable.
// ... Then test the result for escape.
ConsoleKeyInfo info = Console.ReadKey();
if (info.Key == ConsoleKey.Escape)
{
Console.WriteLine("You pressed escape!");
}
// Call ReadKey again and test for the letter a.
info = Console.ReadKey();
if (info.KeyChar == 'a')
{
Console.WriteLine("You pressed a");
}
// Call ReadKey again and test for control-X.
// ... This implements a shortcut sequence.
info = Console.ReadKey();
if (info.Key == ConsoleKey.X &&
info.Modifiers == ConsoleModifiers.Control)
{
Console.WriteLine("You pressed control X");
}
Console.Read();
}
}
Output
(Keys were pressed)
... Press escape, a, then control X
?You pressed escape!
aYou pressed a
?You pressed control X