osmancode
2/21/2018 - 7:26 PM

Navigate between console items by keyboard arrows in C#

Navigate between console items by keyboard arrows in C#

class Menu
    {

        private Dictionary<int, string> options = new Dictionary<int, string>();

        private int activeItem = 1;

        public Menu()
        {
            this.options.Add(1, "Plus");
            this.options.Add(2, "Minus");
            this.options.Add(3, "Devide");        
            this.options.Add(4, "History");
        }

        public void RenderMenu()
        {
            Console.Clear();
            Console.WriteLine(this.options.Count);
            Console.WriteAscii("My Calculator", Color.Yellow);
            Console.WriteLine("Please use keyboard arrows to navigate between menu items:", Color.White);
            foreach (KeyValuePair<int, string> item in this.options)
            {
                string active = item.Key == this.activeItem ? "*" : " ";
                Console.WriteLine("({0}) {1}", Color.White, active, item.Value);
            }
            this.handleMenuNavigation();
        }

        public void handleMenuNavigation()
        {
            switch (Console.ReadKey(false).Key)
            {
                case ConsoleKey.Enter:
                    {
                        // Call the selected option.
                        this.CallOption();
                        return;
                    }
                case ConsoleKey.DownArrow:
                    {
                        if (this.activeItem < this.options.Count)
                        {
                            this.activeItem++;
                        }
                        else
                        {
                            this.activeItem = 1;
                        }
                        this.RenderMenu();
                        break;
                    }
                case ConsoleKey.UpArrow:
                    {
                        if (this.activeItem > 1)
                        {
                            this.activeItem--;
                        }
                        else
                        {
                            this.activeItem  = this.options.Count;
                        }
                        this.RenderMenu();
                        break;
                    }

            }
        
        }

        private void CallOption()
        {
            throw new NotImplementedException();
        }
    }