Mar*_*ers 223
是.看到这篇文章.这是一个例子:
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("White on blue.");
Run Code Online (Sandbox Code Playgroud)
Dar*_*rov 109
class Program
{
static void Main()
{
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("White on blue.");
Console.WriteLine("Another line.");
Console.ResetColor();
}
}
Run Code Online (Sandbox Code Playgroud)
取自这里.
Rog*_*ill 49
以上评论都是可靠的回复,但请注意它们不是线程安全的.如果您使用多个线程写入控制台,更改颜色将添加一个竞争条件,可以创建一些奇怪的输出.虽然修复起来很简单:
public class ConsoleWriter
{
private static object _MessageLock= new object();
public void WriteMessage(string message)
{
lock (_MessageLock)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine(message);
Console.ResetColor();
}
}
}
Run Code Online (Sandbox Code Playgroud)
sil*_*ire 19
我创建了一个小插件(可在NuGet上使用),允许您在控制台输出中添加任何颜色(如果您的终端支持)颜色,而不受传统解决方案的限制.
它的工作原理是扩展String
对象,语法非常简单:
"colorize me".Pastel("#1E90FF");
Run Code Online (Sandbox Code Playgroud)
支持前景色和背景色.
Uwe*_*ayr 18
我发现对控制台输出片段进行着色的最简单方法是在 Windows 控制台中使用ANSI 转义序列。
public static int Main(string[] args)
{
string NL = Environment.NewLine; // shortcut
string NORMAL = Console.IsOutputRedirected ? "" : "\x1b[39m";
string RED = Console.IsOutputRedirected ? "" : "\x1b[91m";
string GREEN = Console.IsOutputRedirected ? "" : "\x1b[92m";
string YELLOW = Console.IsOutputRedirected ? "" : "\x1b[93m";
string BLUE = Console.IsOutputRedirected ? "" : "\x1b[94m";
string MAGENTA = Console.IsOutputRedirected ? "" : "\x1b[95m";
string CYAN = Console.IsOutputRedirected ? "" : "\x1b[96m";
string GREY = Console.IsOutputRedirected ? "" : "\x1b[97m";
string BOLD = Console.IsOutputRedirected ? "" : "\x1b[1m";
string NOBOLD = Console.IsOutputRedirected ? "" : "\x1b[22m";
string UNDERLINE = Console.IsOutputRedirected ? "" : "\x1b[4m";
string NOUNDERLINE = Console.IsOutputRedirected ? "" : "\x1b[24m";
string REVERSE = Console.IsOutputRedirected ? "" : "\x1b[7m";
string NOREVERSE = Console.IsOutputRedirected ? "" : "\x1b[27m";
Console.WriteLine($"This is {RED}Red{NORMAL}, {GREEN}Green{NORMAL}, {YELLOW}Yellow{NORMAL}, {BLUE}Blue{NORMAL}, {MAGENTA}Magenta{NORMAL}, {CYAN}Cyan{NORMAL}, {GREY}Grey{NORMAL}! ");
Console.WriteLine($"This is {BOLD}Bold{NOBOLD}, {UNDERLINE}Underline{NOUNDERLINE}, {REVERSE}Reverse{NOREVERSE}! ");
}
Run Code Online (Sandbox Code Playgroud)
输出:
该NOBOLD
代码确实是“正常强度”。有关详细信息,请参阅链接的维基百科页面上的“SGR(选择图形再现)参数”部分。
如果输出被重定向,重定向测试会避免将转义序列输出到文件中。如果用户的配色方案不是黑底白字,则不会重置,但您可以使用控制台功能在程序开始和结束时保存/恢复用户的配色方案(如果有的话)。
equ*_*man 11
是的,这很简单,也很容易.定义第一个默认颜色.
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.White;
Console.Clear();
Run Code Online (Sandbox Code Playgroud)
Console.Clear()
为了设置新的控制台颜色很重要.如果您不执行此步骤,则在询问值时可以看到组合颜色Console.ReadLine()
.
然后你可以改变每个印刷品的颜色:
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Red text over black.");
Run Code Online (Sandbox Code Playgroud)
完成程序后,请记住在完成时重置控制台颜色:
Console.ResetColor();
Console.Clear();
Run Code Online (Sandbox Code Playgroud)
现在使用netcore我们还有另一个问题,如果你想"保留"用户体验,因为终端在每个操作系统上有不同的颜色.
我正在创建一个用文本格式解决这个问题的库:颜色,对齐等等.随意使用和贡献.
https://github.com/deinsoftware/colorify/也可以作为NuGet包提供
Wal*_*osz 11
这是我为编写带有内联颜色更改的控制台消息而编写的简单方法。它只支持一种颜色,但它符合我的需求。
// 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();
}
Run Code Online (Sandbox Code Playgroud)
这是使用dotnet 的新字符串插值功能的优雅实现。
[InterpolatedStringHandler]
public ref struct ConsoleInterpolatedStringHandler
{
private static readonly Dictionary<string, ConsoleColor> colors;
private readonly IList<Action> actions;
static ConsoleInterpolatedStringHandler() =>
colors = Enum.GetValues<ConsoleColor>().ToDictionary(x => x.ToString().ToLowerInvariant(), x => x);
public ConsoleInterpolatedStringHandler(int literalLength, int formattedCount)
{
actions = new List<Action>();
}
public void AppendLiteral(string s)
{
actions.Add(() => Console.Write(s));
}
public void AppendFormatted<T>(T t)
{
actions.Add(() => Console.Write(t));
}
public void AppendFormatted<T>(T t, string format)
{
if (!colors.TryGetValue(format, out var color))
throw new InvalidOperationException($"Color '{format}' not supported");
actions.Add(() =>
{
Console.ForegroundColor = color;
Console.Write(t);
Console.ResetColor();
});
}
internal void WriteLine() => Write(true);
internal void Write() => Write(false);
private void Write(bool newLine)
{
foreach (var action in actions)
action();
if (newLine)
Console.WriteLine();
}
}
Run Code Online (Sandbox Code Playgroud)
要使用它,请创建一个类,例如ExtendedConsole
:
internal static class ExtendedConsole
{
public static void WriteLine(ConsoleInterpolatedStringHandler builder)
{
builder.WriteLine();
}
public static void Write(ConsoleInterpolatedStringHandler builder)
{
builder.Write();
}
}
Run Code Online (Sandbox Code Playgroud)
然后,像这样使用它:
var @default = "default";
var blue = "blue";
var green = "green";
ExtendedConsole.WriteLine($"This should be {@default}, but this should be {blue:blue} and this should be {green:green}");
Run Code Online (Sandbox Code Playgroud)
同时为多个单词着色的示例方法。
private static void WriteColor(string str, params (string substring, ConsoleColor color)[] colors)
{
var words = Regex.Split(str, @"( )");
foreach (var word in words)
{
(string substring, ConsoleColor color) cl = colors.FirstOrDefault(x => x.substring.Equals("{" + word + "}"));
if (cl.substring != null)
{
Console.ForegroundColor = cl.color;
Console.Write(cl.substring.Substring(1, cl.substring.Length - 2));
Console.ResetColor();
}
else
{
Console.Write(word);
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
WriteColor("This is my message with new color with red", ("{message}", ConsoleColor.Red), ("{with}", ConsoleColor.Blue));
Run Code Online (Sandbox Code Playgroud)
输出:
只是为了添加上面所有使用的答案Console.WriteLine
:在同一行文本上更改颜色,例如编写:
Console.Write("This test ");
Console.BackgroundColor = bTestSuccess ? ConsoleColor.DarkGreen : ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine((bTestSuccess ? "PASSED" : "FAILED"));
Console.ResetColor();
Run Code Online (Sandbox Code Playgroud)
我开发了一个名为 cConsole 的小型有趣类库,用于彩色控制台输出。
用法示例:
const string tom = "Tom";
const string jerry = "Jerry";
CConsole.WriteLine($"Hello {tom:red} and {jerry:green}");
Run Code Online (Sandbox Code Playgroud)
它使用 C# FormattableString、IFormatProvider 和 ICustomFormatter 接口的一些功能来设置文本切片的前景色和背景色。您可以在此处
查看 cConsole 源代码
是的,可以如下。这些颜色可以在控制台应用程序中使用,以红色等形式查看一些错误。
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
Run Code Online (Sandbox Code Playgroud)