ModelingDebug/ModeSwitch.cs
2024-08-29 09:05:13 +08:00

84 lines
2.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Debug;
public class ModeSwitch
{
public event Action<int>? Enter;
private readonly string[] str = ["退出"];
private readonly int mode = 0;
public ModeSwitch(string title, string[] a, Action<int> Enter)
{
this.Enter = Enter;
str = a;
Console.WriteLine(title);
for (int i = 0; i < str.Length; i++)
{
Console.WriteLine($"{i}.{str[i]}");
}
do
{
Console.SetCursorPosition(CalculateActualLength($"{mode}.{str[mode]}") + 1, mode + 1);
Console.Write('>');
var key = Console.ReadKey(true);
Console.SetCursorPosition(CalculateActualLength($"{mode}.{str[mode]}") + 1, mode + 1);
Console.Write(' ');
if (key.Key >= ConsoleKey.D0 && key.Key <= ConsoleKey.D9)
{
int v1 = int.Parse(key.KeyChar.ToString());
if (v1 >= 0 && v1 < str.Length)
mode = v1;
}
else
switch (key.Key)
{
case ConsoleKey.UpArrow:
case ConsoleKey.W:
mode--;
break;
case ConsoleKey.S:
case ConsoleKey.DownArrow:
mode++;
break;
case ConsoleKey.Enter:
Enter?.Invoke(mode);
return;
default:
break;
}
mode = int.Max(0, int.Min(str.Length - 1, mode));
} while (true);
//Console.CursorVisible = false;
}
private static int CalculateActualLength(string text)
{
Encoding encoding = Encoding.UTF8;
int length = 0;
foreach (char c in text)
{
byte[] bytes = encoding.GetBytes(c.ToString());
if (bytes.Length > 1) // 汉字或宽字符
length += 2;
else
length += 1;
}
return length;
}
public static void New(string title, string[] a, Action<int> Enter)
{
_ = new ModeSwitch(title, a, Enter);
}
}