如何提高.NET控制檯應用體驗?

原文:Upgrade Your .NET Console App Experience
做者:Khalid Abuhakmeh
譯文:Lamond Lushell

在.NET生態系統中,控制檯程序的表現相對較差。一般來講,這種項目常常做爲Demo演示使用。如今是時候讓控制檯應用程序獲得其應有的尊重了。編程

終端技術的發展開啓了加強用戶體驗的復興。 ITerm2, Hyper, Windows Terminal,全部這些工具都爲單調的控制檯體驗增長了一些趣味。 雖然這些工具都容許用戶定製本身體驗,可是對於開發人員來講,他們還但願向控制檯應用程序中添加一些編程風格。c#

在本篇博文中,咱們將一塊兒看一下如何使用一些出色的開源項目爲咱們的控制檯程序增添趣味。這裏說明的順序並不代表項目的優劣,他們都是改善咱們控制檯程序體驗的優秀方案。工具

Colorful.Console

Colorful.Console是一個Nuget包,它能夠加強咱們對控制檯輸出文字樣式的控制。咱們可使用System.Drawing.Color中定義的顏色來定義控制檯程序的配色方案。佈局

using System;
using System.Drawing;
using Console = Colorful.Console;
...
...
Console.WriteLine("console in pink", Color.Pink);
Console.WriteLine("console in default");

除此以外,Colorful.Console還容許咱們使用FIGlet字體編寫帶顏色的ASCII碼輸出字體

FIGLet: http://www.figlet.org/動畫

FigletFont font = FigletFont.Load("chunky.flf");
Figlet figlet = new Figlet(font);

Console.WriteLine(figlet.ToAscii("Belvedere"), ColorTranslator.FromHtml("#8AFFEF"));
Console.WriteLine(figlet.ToAscii("ice"), ColorTranslator.FromHtml("#FAD6FF"));
Console.WriteLine(figlet.ToAscii("cream."), ColorTranslator.FromHtml("#B8DBFF"));

這個輸出的結果徹底就是黑客的夢想。ui

我建議你訪問一下colorful.console的官方站點,瞭解這個庫能實現的全部效果,以便更好的改善控制檯程序的體驗。this

Colorful.Console: http://colorfulconsole.com/code

ConsoleTables

ConsoleTables包是我(做者)本身編寫的,這裏有一點厚顏無恥^.^。 使用這個庫,可讓開發人員很輕鬆的將一組對象以表格的形式展現在控制檯中。

static void Main(String[] args)
{
    var table = new ConsoleTable("one", "two", "three");
    table.AddRow(1, 2, 3)
         .AddRow("this line should be longer", "yes it is", "oh");

    table.Write();
    Console.WriteLine();

    var rows = Enumerable.Repeat(new Something(), 10);

    ConsoleTable
        .From<Something>(rows)
        .Configure(o => o.NumberAlignment = Alignment.Right)
        .Write(Format.Alternative);

    Console.ReadKey();
}

之前,誰不但願能在控制檯中輸出一個表格呢?

FORMAT: Default:

 --------------------------------------------------
 | one                        | two       | three |
 --------------------------------------------------
 | 1                          | 2         | 3     |
 --------------------------------------------------
 | this line should be longer | yes it is | oh    |
 --------------------------------------------------

 Count: 2


FORMAT: Alternative:

+----------------------------+-----------+-------+
| one                        | two       | three |
+----------------------------+-----------+-------+
| 1                          | 2         | 3     |
+----------------------------+-----------+-------+
| this line should be longer | yes it is | oh    |
+----------------------------+-----------+-------+

自從ConsoleTables發佈以來,許多開發人員已經研發出本身的控制檯表格庫了。有一些甚至更好,你能夠自行去查找一下。

ShellProgressBar

和須要其餘應用程序同樣,控制檯程序也能夠執行長時任務。ShellProgressBar是一個很是棒的庫,使用它,你能夠在控制檯輸出一些很是驚豔的進度條。並且,ShellProgressBar是能夠實現進度條的嵌套使用。例如,以下GIF動畫中展現的效果。

ShellProgressBar使用起來至關的直接。

const int totalTicks = 10;
var options = new ProgressBarOptions
{
    ProgressCharacter = '─',
    ProgressBarOnBottom = true
};
using (var pbar = new ProgressBar(totalTicks, "Initial message", options))
{
    pbar.Tick(); //will advance pbar to 1 out of 10.
    //we can also advance and update the progressbar text
    pbar.Tick("Step 2 of 10"); 
}

謝謝你, Martijin Larrman, 這真的是一個很是好用的庫。

GUI.CS

GUI.CS是一個很是棒的控制檯UI工具包。它提供了一個功能完善的工具箱,開發人員可使用它構建早期控制檯常見的一種用戶界面。

這個UI工具箱提供了以下控件:

  • Buttons
  • Labels
  • Text Entry
  • Text View
  • User Inputs
  • Windows
  • Menus
  • ScrollBars

使用它,開發人員能夠在控制檯應用中實現一些使人難以置信的效果。這個庫是由Miguel De Icaza編寫的,是控制檯技術的巔峯之做,下面讓咱們一塊兒來看一個實例程序。

using Terminal.Gui;

class Demo {
    static void Main ()
    {
        Application.Init ();
        var top = Application.Top;

    // 建立頂級窗體
        var win = new Window ("MyApp") {
        X = 0,
        Y = 1, // 預留菜單行

        // 使用Dim.Fill(), 它能夠自動調整窗體大小,實現自適應,而無需手動勇於
        Width = Dim.Fill (),
        Height = Dim.Fill ()
    };
        top.Add (win);

    // 建立一個菜單
        var menu = new MenuBar (new MenuBarItem [] {
            new MenuBarItem ("_File", new MenuItem [] {
                new MenuItem ("_New", "Creates new file", NewFile),
                new MenuItem ("_Close", "", () => Close ()),
                new MenuItem ("_Quit", "", () => { if (Quit ()) top.Running = false; })
            }),
            new MenuBarItem ("_Edit", new MenuItem [] {
                new MenuItem ("_Copy", "", null),
                new MenuItem ("C_ut", "", null),
                new MenuItem ("_Paste", "", null)
            })
        });
        top.Add (menu);

    var login = new Label ("Login: ") { X = 3, Y = 2 };
    var password = new Label ("Password: ") {
            X = Pos.Left (login),
        Y = Pos.Top (login) + 1
        };
    var loginText = new TextField ("") {
                X = Pos.Right (password),
                Y = Pos.Top (login),
                Width = 40
        };
        var passText = new TextField ("") {
                Secret = true,
                X = Pos.Left (loginText),
                Y = Pos.Top (password),
                Width = Dim.Width (loginText)
        };
    
    // 添加一些其餘控件
    win.Add (
        // 這是我最喜歡的佈局
        login, password, loginText, passText,

        // 這裏使用了絕對定位
            new CheckBox (3, 6, "Remember me"),
            new RadioGroup (3, 8, new [] { "_Personal", "_Company" }),
            new Button (3, 14, "Ok"),
            new Button (10, 14, "Cancel"),
            new Label (3, 18, "Press F9 or ESC plus 9 to activate the menubar"));

        Application.Run ();
    }
}

總結

做爲開發人員,咱們能夠沉迷於GUI, 這是理所固然的,它使咱們更有生產力。可是控制檯應用程序一樣也很強大。下次當你編寫控制檯程序的時候,你能夠考慮使用以上介紹的某些庫,以便爲你的控制檯應用增添色彩。

相關文章
相關標籤/搜索