从以前的程序中保存标准输出

问题描述 投票:0回答:2

我目前正在尝试创建一个控制台菜单系统,允许用户使用键盘上的箭头键进行向上和向下选择。但是,当显示此菜单时,我希望控制台完全清晰,以便只能看到菜单,然后显示菜单出现之前的控制台。

有没有办法保存此输出或实现类似的效果,以便在用户做出选择后控制台不会被修改?

c# console console-application
2个回答
0
投票

无法在 Windows 中读取标准输出,因此无法保存控制台输出、创建新控制台或为程序编写一个包装器来打印文本并将其保存在文件中


0
投票

NuGet 包Spectre.Console提供了菜单组件和方法来记录菜单中的用户操作。

以下显示使用模拟数据的菜单。

AnsiConsole.Record
开始录制,同时
AnsiConsole.ExportText
已做出选择。

代码是使用net8.0编写的

namespace MenuFuelApp;

internal partial class Program
{
    static void Main()
    {
        AnsiConsole.Record();
        MenuItem selection = new();
        while (selection.Id > -1)
        {
            Console.Clear();
            // display menu, get selection
            selection = AnsiConsole.Prompt(MenuOperations.MainMenu());

            // -1 is exiting selection
            if (selection.Id != -1)
            {
                DisplayFuelType(selection);
            }
            else
            {
                var txt = AnsiConsole.ExportText();
                if (string.IsNullOrWhiteSpace(txt))
                {
                    // user exited without selection
                }
                else
                {
                    /*
                     * at least one selection was made
                     * can log it to say a text file
                     */
                }
                return;
            }
        }

    }

    private static void DisplayFuelType(MenuItem menuItem)
    {
        Console.Clear();
        AnsiConsole.MarkupLine(menuItem.Id > -1
            ? $"Fuel type [cyan]{menuItem.Text}[/] at " +
              $"[cyan]{menuItem.Price:C}[/] Press a key for menu"
            : "[yellow]Nothing selected[/] Press a key for menu");
        Console.ReadLine();
    }
}
// move to a separate file
public class MenuItem
{
    public int Id { get; set; }
    public string Text { get; set; }
    public double Price { get; set; }
    // what to display in menu
    public override string ToString() => Text;
}

// move to a separate file
class MenuOperations
{
    
    // Create menu with mocked items
    public static SelectionPrompt<MenuItem> MainMenu()
    {
        // style of menu
        SelectionPrompt<MenuItem> menu = new()
        {
            HighlightStyle = new Style(Color.White, Color.Blue, Decoration.None)
        };

        menu.Title("[white on blue]Select fuel type[/]");
        menu.AddChoices(MenuItems());

        return menu;
    }
    // For a real app, load items from a file or database
    public static List<MenuItem> MenuItems() =>
    [
        new() { Id = 0, Text = "Diesel", Price = 3.99 },
        new() { Id = 1, Text = "Gasoline", Price = 3.45 },
        new() { Id = 2, Text = "Ethanol", Price = 2.99 },
        new() { Id = -1, Text = "Exit" }
    ];
}

enter image description here

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.