写一个小的命令行工具,用不同的颜色输出会很好。这可能吗?


当前回答

只是补充上面的答案,所有使用控制台。要改变同一行文本的颜色,可以这样写:

Console.Write("This test ");
Console.BackgroundColor = bTestSuccess ? ConsoleColor.DarkGreen : ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine((bTestSuccess ? "PASSED" : "FAILED"));
Console.ResetColor();

其他回答

是的,可能如下所示。这些颜色可以在控制台应用程序中使用,以红色等方式查看一些错误。

Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;//after this line every text will be white on blue background
Console.WriteLine("White on blue.");
Console.WriteLine("Another line.");
Console.ResetColor();//reset to the defoult colour
class Program
{
    static void Main()
    {
        Console.BackgroundColor = ConsoleColor.Blue;
        Console.ForegroundColor = ConsoleColor.White;
        Console.WriteLine("White on blue.");
        Console.WriteLine("Another line.");
        Console.ResetColor();
    }
}

从这里拍的。

我只是想在使用console。writeline()时调整文本颜色; 所以我不得不写

Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.WriteLine("my message");
Console.ResetColor();

每次我想写点什么

所以我发明了我的WriteLine()方法,并一直在Program类中使用它而不是console。

public static void WriteLine(string buffer, ConsoleColor foreground = ConsoleColor.DarkGreen, ConsoleColor backgroundColor = ConsoleColor.Black)
{
   Console.ForegroundColor = foreground;
   Console.BackgroundColor = backgroundColor;
   Console.WriteLine(buffer);
   Console.ResetColor();
}

为了让它更简单,我还写了一个Readline()方法,像这样:

public static string ReadLine()
{
   var line = Console.ReadLine();
   return line ?? string.Empty;
}

现在我们要做的就是在控制台中写入或读取一些东西:

static void Main(string[] args) {
   WriteLine("hello this is a colored text");
   var answer = Readline();
}

是的,这很简单,也有可能。定义第一个默认颜色。

Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.White;
Console.Clear();

console . clear()对于设置新的控制台颜色很重要。如果不执行此步骤,则在使用Console.ReadLine()请求值时可以看到组合颜色。

然后你可以改变每个打印的颜色:

Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Red text over black.");

当完成程序时,记得在完成时重置控制台颜色:

Console.ResetColor();
Console.Clear();

现在对于netcore,我们有另一个问题,如果你想“保留”用户体验,因为终端在每个操作系统上有不同的颜色。

我正在制作一个库,用文本格式解决这个问题:颜色,对齐和更多。请随意使用和贡献。

https://github.com/deinsoftware/colorify/,也可作为NuGet包

Windows/Linux的颜色(深色):

MacOS的颜色(浅色):

下面是我编写的一个简单方法,用于编写带有内联颜色变化的控制台消息。它只支持一种颜色,但它符合我的需要。

// usage: WriteColor("This is my [message] with inline [color] changes.", ConsoleColor.Yellow);
static void WriteColor(string message, ConsoleColor color)
{
    var pieces = Regex.Split(message, @"(\[[^\]]*\])");

    for(int i=0;i<pieces.Length;i++)
    {
        string piece = pieces[i];
        
        if (piece.StartsWith("[") && piece.EndsWith("]"))
        {
            Console.ForegroundColor = color;
            piece = piece.Substring(1,piece.Length-2);          
        }
        
        Console.Write(piece);
        Console.ResetColor();
    }
    
    Console.WriteLine();
}