116 lines
3.1 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace laba3.Core
{
/// <summary>
/// TUI menu;
/// </summary>
2024-12-14 10:20:38 +04:00
public class Menu
{
2024-12-14 10:20:38 +04:00
private List<MenuOption> options;
private int selected;
private string title;
/// <summary>
/// Constructor of menu;
/// </summary>
/// <param name="title">Title of menu</param>
public Menu(string title)
{
this.title = title;
2024-12-14 10:20:38 +04:00
this.options = new List<MenuOption> { };
}
2024-12-14 10:20:38 +04:00
/// <summary>
/// Get options list
/// </summary>
/// <returns></returns>
public List<MenuOption> GetOptions() { return this.options; }
/// <summary>
/// Get title string
/// </summary>
/// <returns></returns>
public string GetTitle() { return this.title; }
/// <summary>
/// Add option to menu;
/// </summary>
/// <param name="name">Name of option</param>
/// <param name="action">Action, runs if option selected</param>
public void AddOption(string name, Action action)
{
2024-12-14 10:20:38 +04:00
this.options.Add(new MenuOption(name, action));
}
/// <summary>
/// Run menu;
/// Console will be clean!;
/// </summary>
public void RunMenu()
{
selected = 0;
this.PrintMenu();
ConsoleKeyInfo keyinfo;
do
{
keyinfo = Console.ReadKey();
if (keyinfo.Key == ConsoleKey.DownArrow)
{
if (selected + 1 < options.Count)
{
selected++;
this.PrintMenu();
}
}
if (keyinfo.Key == ConsoleKey.UpArrow)
{
if (selected > 0)
{
selected--;
this.PrintMenu();
}
}
if (keyinfo.Key == ConsoleKey.Enter)
{
Console.Clear();
options[selected].Action.Invoke();
}
} while (keyinfo.Key != ConsoleKey.Enter);
}
private void PrintMenu()
{
Console.Clear();
Console.WriteLine(title);
int optionIndex = 0;
2024-12-14 10:20:38 +04:00
foreach (MenuOption option in options)
{
string pointer = optionIndex == selected ? " ->" : " ";
Console.WriteLine($"{pointer}{option.Name}");
optionIndex++;
}
}
2024-12-14 10:20:38 +04:00
/// <summary>
/// Menu option struct;
/// </summary>
public struct MenuOption
{
public string Name { get; }
public Action Action { get; }
2024-12-14 10:20:38 +04:00
public MenuOption(string name, Action action)
{
Name = name;
Action = action;
}
}
}
}