Read User Input from the Console - CSharp Language Basics

CSharp examples for Language Basics:Console

Description

Read User Input from the Console

Demo Code

using System;//from w w  w .  j a  v  a 2s.c  o  m
using System.Collections.Generic;
using System.Linq;
using System.Text;
class MainClass
{
   static void Main(string[] args)
   {
      ConsoleKeyInfo key;
      bool secret = false;
      List<char> input = new List<char>();
      string msg = "Enter characters and press Escape to see input." +
      "\nPress F1 to enter/exit Secret mode and Alt-X to exit.";
      Console.WriteLine(msg);
      do
      {
         key = Console.ReadKey(true);
         if (key.Key == ConsoleKey.F1)
         {
            if (secret)
            {
               secret = false;
            }
            else
            {
               secret = true;
            }
         }
         if (key.Key == ConsoleKey.Backspace)
         {
            if (input.Count > 0)
            {
               input.RemoveAt(input.Count - 1);
               Console.Write(key.KeyChar);
               Console.Write(" ");
               Console.Write(key.KeyChar);
            }
         }
         else if (key.Key == ConsoleKey.Escape)
         {
            Console.WriteLine("Input: {0}\n\n", new String(input.ToArray()));
            Console.WriteLine(msg);
            input.Clear();
         }
         else if (key.Key >= ConsoleKey.A && key.Key <= ConsoleKey.Z)
         {
            input.Add(key.KeyChar);
            if (secret)
            {
               Console.Write("inner mode");
            }
            else
            {
               Console.Write(key.KeyChar);
            }
         }
      } while (key.Key != ConsoleKey.X || key.Modifiers != ConsoleModifiers.Alt);
   }

}

Result


Related Tutorials