Donnerstag, 11. Dezember 2014

[C#] Switch-case based Console Menu

In my opinion its annoying validating the console input of the user. This little snippet will offer a menu where the user can navigate between the possible options with the arrow keys (up and down) and select one pressing enter:


The function takes a string which will be printed on top of the options (a description?) and a string list containing the selectable options. the returned int will hold the index of the selected item.

printMenu function:
 private static int printMenu(string parHead, List<string> parOptions)  
 {  
      Console.WriteLine(parHead);  
      int count = 0;  
      bool firstRun = true;  
      bool bEnd = false;  
      while (true)  
      {  
           if (!firstRun)  
           {  
                switch (Console.ReadKey(true).Key)  
                {  
                     case ConsoleKey.UpArrow:  
                          count = (count - 1) % parOptions.Count;  
                          if (count < 0)  
                          {  
                               count = parOptions.Count - 1;  
                          }  
                          break;  
                     case ConsoleKey.DownArrow:  
                          count = (count + 1) % parOptions.Count;  
                          break;  
                     case ConsoleKey.Enter:  
                          bEnd = true;  
                          break;  
                }  
                ClearConsoleLines(parOptions.Count);  
           }  
           char select = ' ';  
           for (int i = 0; i < parOptions.Count; i++)  
           {  
                if (count == i)  
                {  
                     select = 'x';  
                }  
                else  
                {  
                     select = ' ';  
                }  
                Console.WriteLine(parOptions[i] + new string('\t', 1) + "[" + select + "]");  
           }  
           firstRun = false;  
           if (bEnd) break;  
      }  
      return count;  
 }  

ClearConsoleLines function:
 public static void ClearConsoleLines(int parLines)  
 {  
      for (int i = 0; i < parLines; i++)  
      {  
           Console.SetCursorPosition(0, Console.CursorTop - 1);  
           int currentLineCursor = Console.CursorTop;  
           Console.SetCursorPosition(0, Console.CursorTop);  
           Console.Write(new string(' ', Console.WindowWidth));  
           Console.SetCursorPosition(0, currentLineCursor);  
      }  
 }  

Example usage:
 List<string> listExample = new List<string>();  
 listExample.Add("option1");  
 listExample.Add("option2");  
 listExample.Add("option3");  
 listExample.Add("option4");  
 listExample.Add("option5");  
 listExample.Add("option6");  
 listExample.Add("option7");  
 int res = printMenu("Select one:", listExample);  
 Console.WriteLine("\n" + listExample[res] + "\n");  

Keine Kommentare:

Kommentar veröffentlichen