≡ Menu




Some thing about Console.Readkey()

Last day while studying for Dot net certification I found  a good function “ReadKey” .
.It reads single character with out pressing enter key as we did in Console.Read() .
Where it is like Console.ReadKey();
When executed statement reach at ReadKey statement it waits for key press. When key press keystoke occur and it return pressed key immediately. No need to press Enter key.
So ReadKeys() used in real-time.
 
Return Values :
ReadKeys return value in the form of object ConsolekeyInfo. It has three read only properties.
1-Char keyChar; ( Contains the equitant character which is pressed )
2-Console key; (Key contains a value from the ConsoleKey enumeration, which is an enumeration of all the keys on the keyboard)
3- ConsoleModifiers Modifiers (Can contain  one of these three Values  “Alt,Ctr, Shift”  which keyboard modifier is Press with the key.  If more than one keyboard modifier is press you can find them in Modifers)
 Advantage : Major advantage it over Readln/Read that it is not lined buffered

Example
using System;

class ReadKeys {
  public static void Main() {
    ConsoleKeyInfo keypress;

    Console.WriteLine(“Enter keystrokes. Enter Q to stop.”);

    do {
      keypress = Console.ReadKey(); // read keystrokes

      Console.WriteLine(” Your key is: ” + keypress.KeyChar);

      // Check for modifier keys.
      if((ConsoleModifiers.Alt & keypress.Modifiers) != 0)
        Console.WriteLine(“Alt key pressed.”);
      if((ConsoleModifiers.Control & keypress.Modifiers) != 0)
        Console.WriteLine(“Control key pressed.”);
      if((ConsoleModifiers.Shift & keypress.Modifiers) != 0)
        Console.WriteLine(“Shift key pressed.”);

    } while(keypress.KeyChar != ‘Q’);
  }
}

{ 0 comments… add one }

Leave a Comment