Using colors in the console, how to store in simplified notation

The code below shows a string in different colors.
But this is a lot of code to enter only one line and repeat the entire program.
How exactly can I simplify this, so I don’t need to write the same code again and again?

Console.ForegroundColor = ConsoleColor.Cyan; Console.Write(">>> Order: "); Console.ResetColor(); Console.Write("Data"); Console.ForegroundColor = ConsoleColor.DarkGreen; Console.Write("Parity"); Console.ForegroundColor = ConsoleColor.Cyan; Console.Write(" <<<"); 

Is there any way to save ... = Console.ForegroundColor = ConsoleColor.Cyan;

"text" + color? + "text"; etc...

Any input is appreciated Regards.

+4
source share
7 answers

It's not entirely clear what you mean, but you can always create helper methods:

 public static void ColoredConsoleWrite(ConsoleColor color, string text) { ConsoleColor originalColor = Console.ForegroundColor; Console.ForegroundColor = color; Console.Write(text); Console.ForegroundColor = originalColor; } 
+19
source

Use can use my Edokan.KaiZen.Colors library. This is a shameless copy of the npm module colors for node.js.

He has some problems, but it works. Actually it works the way you want.

 Console.WriteLine("INFO: ".Cyan().Bold() + " This is just a message"); 
+9
source
Another idea is to implement something like ANSI escape codes , but they are quite extensive, and color is only a small part of them.

Therefore, I would recommend embedding color codes in output lines using the “Unicode Custom Use Area” (PUA) section of the Basic Multilingual Plane (BMP) and basic analyzer / rendering.

By the way, console color settings are global for the process, therefore, if several threads generate color output, each block must be surrounded by a critical section to avoid “color confusion”.

Since its a little longer to install inline, I uploaded a sample source to my site.

+6
source

An ugly but simple solution.

Beginning of the foreground color tag: <*color*> . End of foreground color tag: <*/*> . Background color tag start: <*!color*> . End of background color tag: <*/!*> .

Usage example:

 WriteLineColor("<*!red*><*yellow*>Yellow text<*/*> and <*cyan*>cyan text<*/*> on red background.<*/!*>"); 

Non-case-sensitive list of colors (System.ConsoleColor): black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White.

 static void WriteColor(string str) { var fgStack = new Stack<ConsoleColor>(); var bgStack = new Stack<ConsoleColor>(); var parts = str.Split(new[] { "<*" }, StringSplitOptions.None); foreach (var part in parts) { var tokens = part.Split(new[] { "*>" }, StringSplitOptions.None); if (tokens.Length == 1) { Console.Write(tokens[0]); } else { if (!String.IsNullOrEmpty(tokens[0])) { ConsoleColor color; if (tokens[0][0] == '!') { if (Enum.TryParse(tokens[0].Substring(1), true, out color)) { bgStack.Push(Console.BackgroundColor); Console.BackgroundColor = color; } } else if (tokens[0][0] == '/') { if (tokens[0].Length > 1 && tokens[0][1] == '!') { if (bgStack.Count > 0) Console.BackgroundColor = bgStack.Pop(); } else { if (fgStack.Count > 0) Console.ForegroundColor = fgStack.Pop(); } } else { if (Enum.TryParse(tokens[0], true, out color)) { fgStack.Push(Console.ForegroundColor); Console.ForegroundColor = color; } } } for (int j = 1; j < tokens.Length; j++) Console.Write(tokens[j]); } } } static void WriteLineColor(string str) { WriteColor(str); Console.WriteLine(); } static void WriteColor(string str, params object[] arg) { WriteColor(String.Format(str, arg)); } static void WriteLineColor(string str, params object[] arg) { WriteColor(String.Format(str, arg)); Console.WriteLine(); } 
+2
source

You can use the CsConsoleFormat † library to format console output with colors.

Here is what your code would look like:

 using static System.ConsoleColor; ConsoleRenderer.RenderDocument(new Document().AddChildren( new Span(">>> Order: ") { Color = Cyan }, new Span("Data") { Color = Gray }, new Span("Parity") { Color = DarkGreen }, new Span(" <<<") { Color = Cyan } )); 

or alternatively:

 ConsoleRenderer.RenderDocument(new Document().AddChildren( new Span { Color = Cyan }.AddChildren( ">>> Order: ", new Span("Data") { Color = Gray }, new Span("Parity") { Color = DarkGreen }, " <<<" ) )); 

or, using an auxiliary code (see below):

 ColoredSpans.Render(">>> Order: ".Cyan(), "Data".Gray(), "Parity".DarkGreen(), " <<<".Cyan()); 

The two best methods, although not very narrow, have many advantages:

  • Make intuition clear and maintain a hierarchy, for example, child intervals added to the parent range inherit parent colors.
  • Unlike the ColoredConsoleWrite helper method, generate a complete document that can be adjusted as a whole (for example, word wrap, background).
  • Do not rely on the concept of "reverse console color," which is alien to .NET developers on Windows to set the background color.

If you need more specific code (for example, you write a lot of formatted paragraphs with many words highlighted), you can use this collection of helper methods inspired by Edokan.KaiZen.Colors to write code, as in the third example above:

 public static class Spans { public static Span Black(this string text) => new Span(text) { Color = ConsoleColor.Black }; public static Span DarkBlue(this string text) => new Span(text) { Color = ConsoleColor.DarkBlue }; public static Span DarkGreen(this string text) => new Span(text) { Color = ConsoleColor.DarkGreen }; public static Span DarkCyan(this string text) => new Span(text) { Color = ConsoleColor.DarkCyan }; public static Span DarkRed(this string text) => new Span(text) { Color = ConsoleColor.DarkRed }; public static Span DarkMagenta(this string text) => new Span(text) { Color = ConsoleColor.DarkMagenta }; public static Span DarkYellow(this string text) => new Span(text) { Color = ConsoleColor.DarkYellow }; public static Span Gray(this string text) => new Span(text) { Color = ConsoleColor.Gray }; public static Span DarkGray(this string text) => new Span(text) { Color = ConsoleColor.DarkGray }; public static Span Blue(this string text) => new Span(text) { Color = ConsoleColor.Blue }; public static Span Green(this string text) => new Span(text) { Color = ConsoleColor.Green }; public static Span Cyan(this string text) => new Span(text) { Color = ConsoleColor.Cyan }; public static Span Red(this string text) => new Span(text) { Color = ConsoleColor.Red }; public static Span Magenta(this string text) => new Span(text) { Color = ConsoleColor.Magenta }; public static Span Yellow(this string text) => new Span(text) { Color = ConsoleColor.Yellow }; public static Span White(this string text) => new Span(text) { Color = ConsoleColor.White }; public static void Render(object[] elements) => ConsoleRenderer.RenderDocument(new Document().AddChildren(elements)); } 

† CsConsoleFormat was developed by me.

+1
source

Here is my contribution, albeit in Visual Basic:

 Sub WriteColor(ByRef part1 As String, ByRef part2 As String) Console.Write(part1) Console.ForegroundColor = ConsoleColor.Green Console.WriteLine(part2) Console.ResetColor() End Sub 

I call the above code as follows:

 WriteColor("DEBUGMODE INFO: SQL query statement result = ", result.ToString) 

The green color allows me to select the result of the request in all the other debugging messages that I print. Hope this helps. Obviously, a more general solution, perhaps one that allows a variable number of arguments, would be more useful, but even this specific code helps me avoid repetition and makes life easier.

0
source

I created a small plugin (available on NuGet ) that makes it easy to wrap your lines in ANSI color codes. You can specify any color that you like, but it depends on the terminal, regardless of whether it supports it or not. If this is not the case, it will approach the closest color. 24-bit colors are available on the Windows 10 command line from v1511.

enter image description here

It works by extending the String object, and the syntax is very simple:

 "color me".Pastel("#1E90FF"); 

After that, it is ready to print on the console.

0
source

Source: https://habr.com/ru/post/1307770/


All Articles