ANSI-Coloring Console with .NET Output

I am trying to create color console output using ANSI escape codes with the following minimal C # program:

using System; // test.cs class foo { static void Main(string[] args) { Console.WriteLine("\x1b[36mTEST\x1b[0m"); } } 

I am running Ansicon v1.66 ​​on Windows 7 x64 using csc.exe (Microsoft (R) Visual C # Compiler version 4.6.0081.0).

The color output works fine in this configuration; Ansicon itself works flawlessly.

For cross validation, I use one-liner node.js, which is 100% equivalent to the C # program:

 // test.js console.log("\x1b[36mTEST\x1b[0m"); 

And an even simpler, manual text file:

text file hex editor screenshot

Both of which, correctly do the expected thing: Print a teal -colored string "TEST":

enter image description here

Only test.exe, which I built with csc, prints something else. What for?

+6
source share
2 answers

Your program must be compiled for /platform:x64 if you are using AnsiCon x64 and /platform:x86 if you are using AnsiCon x86 / 32 bit. The exact reason is the mystery ...

Originally, I thought you needed all of this:

You need to capture StandardOutput and let Console.WriteLine assume that you are writing the file, not the console, and using ASCII encoding.

Here's how it will work:

  var stdout = Console.OpenStandardOutput(); var con = new StreamWriter(stdout, Encoding.ASCII); con.AutoFlush = true; Console.SetOut(con); Console.WriteLine("\x1b[36mTEST\x1b[0m"); 

.Net Console.WriteLine uses the internal __ConsoleStream , which checks if Console.Out file descriptor or a console descriptor. By default, it uses a console descriptor and therefore writes to the console by calling WriteConsoleW . In the notes you will find:

Although an application can use WriteConsole in ANSI mode to write ANSI characters, consoles do not support ANSI escape sequences. However, some functions provide equivalent functionality. For more information, see SetCursorPos, SetConsoleTextAttribute, and GetConsoleCursorInfo.

To write bytes directly to the console without WriteConsoleW , a simple file / stream descriptor, which will be executed by calling OpenStandardOutput , will OpenStandardOutput . By packing this stream into StreamWriter so that we can install it again using Console.SetOut , we are done. Byte sequences are sent to an OutputStream and matched by AnsiCon.

Please note that this can only be used with the appropriate terminal emulator, for example AnsiCon, as shown below:

enter image description here

+5
source

I created a small plugin (available on NuGet ) that allows you to easily wrap strings in ANSI color codes. Foreground and background colors are supported.

enter image description here

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

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

Then the line is ready for printing on the console.

+2
source

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


All Articles