我试图制作一个类似于下面的菜单:
> Thing
Another Thing
Yet Another Thing
Exit
在C#控制台应用程序中,我找了很久但是找不到适用于这种菜单的库或示例代码。
简单来说,我想要做到以下几点:
- 显示一个菜单
- 允许用户使用箭头键[上/下]进行选择
- 当不同选项被选择时执行不同的操作[回车键]
我试图制作一个类似于下面的菜单:
> Thing
Another Thing
Yet Another Thing
Exit
在C#控制台应用程序中,我找了很久但是找不到适用于这种菜单的库或示例代码。
简单来说,我想要做到以下几点:
最重要的是能够捕获输入内容。控制台只能通过清除控制台窗口并重新呈现它来“模拟”交互式菜单。
using System.Collections.Generic;
using System;
using System.Linq;
using System.Threading;
namespace ConsoleApp
{
class Program
{
public static List<Option> options;
static void Main(string[] args)
{
// Create options that you want your menu to have
options = new List<Option>
{
new Option("Thing", () => WriteTemporaryMessage("Hi")),
new Option("Another Thing", () => WriteTemporaryMessage("How Are You")),
new Option("Yet Another Thing", () => WriteTemporaryMessage("Today")),
new Option("Exit", () => Environment.Exit(0)),
};
// Set the default index of the selected item to be the first
int index = 0;
// Write the menu out
WriteMenu(options, options[index]);
// Store key info in here
ConsoleKeyInfo keyinfo;
do
{
keyinfo = Console.ReadKey();
// Handle each key input (down arrow will write the menu again with a different selected item)
if (keyinfo.Key == ConsoleKey.DownArrow)
{
if (index + 1 < options.Count)
{
index++;
WriteMenu(options, options[index]);
}
}
if (keyinfo.Key == ConsoleKey.UpArrow)
{
if (index - 1 >= 0)
{
index--;
WriteMenu(options, options[index]);
}
}
// Handle different action for the option
if (keyinfo.Key == ConsoleKey.Enter)
{
options[index].Selected.Invoke();
index = 0;
}
}
while (keyinfo.Key != ConsoleKey.X);
Console.ReadKey();
}
// Default action of all the options. You can create more methods
static void WriteTemporaryMessage(string message)
{
Console.Clear();
Console.WriteLine(message);
Thread.Sleep(3000);
WriteMenu(options, options.First());
}
static void WriteMenu(List<Option> options, Option selectedOption)
{
Console.Clear();
foreach (Option option in options)
{
if (option == selectedOption)
{
Console.Write("> ");
}
else
{
Console.Write(" ");
}
Console.WriteLine(option.Name);
}
}
}
public class Option
{
public string Name { get; }
public Action Selected { get; }
public Option(string name, Action selected)
{
Name = name;
Selected = selected;
}
}
}