提问人:NibblyPig 提问时间:4/30/2010 更新时间:8/7/2023 访问量:241653
是否可以在 .NET 中以彩色写入控制台?
Is it possible to write to the console in colour in .NET?
答:
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.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("White on blue.");
评论
以上评论都是可靠的回应,但请注意,它们不是线程安全的。如果要使用多个线程写入控制台,则更改颜色将添加争用条件,从而创建一些看起来奇怪的输出。不过,修复起来很简单:
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();
}
}
}
评论
Write
WriteMessage
是的,这很容易,而且是可能的。定义第一个默认颜色。
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 包使用
是的,可以按以下方式进行。这些颜色可以在控制台应用程序中用于查看红色等错误。
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
我创建了一个小型插件(在 NuGet 上可用),它允许您向控制台输出添加任何(如果终端支持)颜色,而不受经典解决方案的限制。
它通过扩展对象来工作,语法非常简单:String
"colorize me".Pastel("#1E90FF");
支持前景色和背景色。
评论
只是为了补充上面所有使用的答案:要更改同一行文本的颜色,请写例如:Console.WriteLine
Console.Write("This test ");
Console.BackgroundColor = bTestSuccess ? ConsoleColor.DarkGreen : ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine((bTestSuccess ? "PASSED" : "FAILED"));
Console.ResetColor();
这是我编写的一个简单的方法,用于编写具有内联颜色更改的控制台消息。它只支持一种颜色,但它符合我的需求。
// 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();
}
评论
message
Console.ForegroundColor
我确实想在我想使用时调整文本颜色所以我不得不写Console.WriteLine();
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.WriteLine("my message");
Console.ResetColor();
每次我想写点什么
所以我发明了我的方法,并继续在程序类中使用它,而不是WriteLine()
Console.WriteLine()
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();
}
同时为多个单词着色的示例方法。
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);
}
}
}
用法:
WriteColor("This is my message with new color with red", ("{message}", ConsoleColor.Red), ("{with}", ConsoleColor.Blue));
输出:
我开发了一个名为 cConsole 的小型有趣的类库,用于彩色控制台输出。
用法示例:
const string tom = "Tom";
const string jerry = "Jerry";
CConsole.WriteLine($"Hello {tom:red} and {jerry:green}");
它使用 C# FormattableString、IFormatProvider 和 ICustomFormatter 接口的一些功能来设置文本切片的前景色和背景色。
您可以在此处查看 cConsole 源代码
评论
下面是使用 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();
}
}
要使用它,请创建一个类,例如:ExtendedConsole
internal static class ExtendedConsole
{
public static void WriteLine(ConsoleInterpolatedStringHandler builder)
{
builder.WriteLine();
}
public static void Write(ConsoleInterpolatedStringHandler builder)
{
builder.Write();
}
}
然后,像这样使用它:
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}");
我发现对控制台输出片段进行着色的最简单方法是在 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}! ");
}
输出:
代码实际上是“正常强度”。有关详细信息,请参阅链接的维基百科页面上的“SGR(选择图形演绎版)参数”部分。NOBOLD
如果输出被重定向,重定向测试可避免将转义序列输出到文件中。如果用户的配色方案不是黑底白字,则不会重置,但如果重要,您可以使用控制台功能在程序的开头和结尾保存/恢复用户的配色方案。
评论
使用这个简单的 C# 代码,您可以演示所有可能的输出颜色并选择所需的颜色。
Type type = typeof(ConsoleColor);
Console.ForegroundColor = ConsoleColor.White;
foreach (var name in Enum.GetNames(type))
{
Console.BackgroundColor = (ConsoleColor)Enum.Parse(type, name);
Console.WriteLine(name);
}
Console.BackgroundColor = ConsoleColor.Black;
foreach (var name in Enum.GetNames(type))
{
Console.ForegroundColor = (ConsoleColor)Enum.Parse(type, name);
Console.WriteLine(name);
}
评论