Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Online post: https://pastebin.com/9NmGvV4y
- // See my more advanced menu here: https://pastebin.com/K4KcHS5u
- using System;
- using System.Diagnostics;
- namespace ConsoleMenu
- {
- internal class Program
- {
- private static void Main(string[] args)
- {
- var indent = " ";
- var outdent = Environment.NewLine + Environment.NewLine;
- var selectedIndex = 0;
- while (true)
- {
- Console.Clear();
- // Print a vertical menu.
- for (var i = 0; i < MENU_OPTIONS.Length; i++)
- {
- var menuOption = MENU_OPTIONS[i];
- WriteMenuEntry(menuOption, i == selectedIndex, indent, outdent);
- }
- // Print a dividing line.
- Console.WriteLine(new String('-', 80));
- // Print a horizontal menu.
- for (var i = 0; i < MENU_OPTIONS.Length; i++)
- {
- var menuOption = MENU_OPTIONS[i];
- WriteMenuEntry(menuOption, i == selectedIndex, indent);
- }
- Console.WriteLine();
- // Process input.
- var userInput = Console.ReadKey();
- switch (userInput.Key)
- {
- case ConsoleKey.LeftArrow:
- case ConsoleKey.UpArrow:
- // Loop around backwards.
- selectedIndex = (selectedIndex - 1 + MENU_OPTIONS.Length) % MENU_OPTIONS.Length;
- break;
- case ConsoleKey.RightArrow:
- case ConsoleKey.DownArrow:
- // Loop around forwards.
- selectedIndex = (selectedIndex + 1) % MENU_OPTIONS.Length;
- break;
- case ConsoleKey.Enter:
- ExecuteMenuEntry(selectedIndex);
- break;
- default:
- Console.WriteLine($"\n{indent}The pressed key '{userInput.Key}' is not associated with a menu function.");
- Pause();
- break;
- }
- }
- }
- private static void WriteMenuEntry(string text, bool highlight, string indent = null, string outdent = null)
- {
- Console.Write(indent);
- if (highlight)
- {
- // Apply selected colors.
- Console.ForegroundColor = ConsoleColor.Black;
- Console.BackgroundColor = ConsoleColor.White;
- }
- Console.Write(text);
- if (highlight)
- {
- // Restore normal colors.
- Console.ForegroundColor = ConsoleColor.White;
- Console.BackgroundColor = ConsoleColor.Black;
- }
- Console.Write(outdent);
- }
- private static void ExecuteMenuEntry(int index)
- {
- // If exit option is selected.
- if (index == MENU_OPTIONS.Length - 1)
- Environment.Exit(0);
- Console.WriteLine($"\n Selected index: {index}");
- Pause();
- }
- private static void Pause()
- {
- // Press any key to continue.
- if (Debugger.IsAttached == false)
- {
- Console.WriteLine();
- Console.Write("Press any key to continue . . . ");
- Console.ReadKey();
- }
- }
- private static readonly string[] MENU_OPTIONS = new string[] {
- " Option 1 ",
- " Option 2 ",
- " Option 3 ",
- " Exit ",
- };
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement