BradleyUffner

Untitled

Dec 18th, 2017
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.87 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace ConsoleApp2
  8. {
  9.     class Program
  10.     {
  11.         private static bool wasEscapePressed = false;
  12.  
  13.         static void Main(string[] args)
  14.         {
  15.             Console.WriteLine("Press ESC at any time to exit the loop");
  16.             while (!wasEscapePressed)
  17.             {
  18.                 Console.Write("Enter your name: ");
  19.                 string name = ReadLineEx(key =>
  20.                 {
  21.                     if (key.Key == ConsoleKey.Escape)
  22.                     {
  23.                         wasEscapePressed = true;
  24.                         return true;
  25.                     }
  26.                     if (key.Key == ConsoleKey.Enter)
  27.                     {
  28.                         return true;
  29.                     }
  30.                     return false;
  31.                 });
  32.  
  33.                 if (wasEscapePressed)
  34.                 {
  35.                     Console.WriteLine("ESCAPE PRESSED!!!");
  36.                 }
  37.                 else
  38.                 {
  39.                     Console.WriteLine("You said your name is " + name);
  40.                 }
  41.             }
  42.  
  43.             Console.WriteLine("Press any key to exit");
  44.             Console.ReadKey();
  45.         }
  46.  
  47.         static string ReadLineEx(Func<ConsoleKeyInfo, bool> isDoneCallback)
  48.         {
  49.             string input = "";
  50.             bool isDone = false;
  51.             wasEscapePressed = false;
  52.  
  53.             while (!isDone)
  54.             {
  55.                 ConsoleKeyInfo key = Console.ReadKey(true);
  56.                 isDone = isDoneCallback(key);
  57.                 if (!isDone)
  58.                 {
  59.                     input += key.KeyChar;
  60.                     Console.Write(key.KeyChar);
  61.                 }
  62.             }
  63.  
  64.             Console.WriteLine();
  65.             return input;
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment