使用 .NET 的 ANSI 着色控制台输出 [英] ANSI-Coloring Console Output with .NET
问题描述
我尝试使用
两者都正确地做预期的事情:打印一个青色色的字符串TEST":
只有我用 csc 构建的 test.exe 会打印其他内容.为什么?
如果您使用 AnsiCon x64 环境并使用 /platform,则您的程序需要针对
如果您使用 AnsiCon x86/32 位版本.确切的原因是个谜.../platform:x64
进行编译:x86
本来我以为你需要这一切:
您需要获取 StandardOutput 并让 Console.WriteLine 相信您写入文件而不是控制台并使用 ASCII 编码.
这是它的工作原理:
var stdout = Console.OpenStandardOutput();var con = new StreamWriter(stdout, Encoding.ASCII);con.AutoFlush = true;Console.SetOut(con);Console.WriteLine("x1b[36mTESTx1b[0m");
.Net Console.WriteLine 使用内部 __ConsoleStream
来检查 Console.Out
是作为文件句柄还是控制台句柄.默认情况下,它使用控制台句柄,因此通过调用
I try to generate colored 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[36mTESTx1b[0m");
}
}
I am running Ansicon v1.66 on Windows 7 x64 with csc.exe (Microsoft (R) Visual C# Compiler version 4.6.0081.0).
Colored output works fine in this configuration; Ansicon itself is working flawlessly.
To cross-check I use a node.js one-liner that is 100% equivalent to the C# program:
// test.js
console.log("x1b[36mTESTx1b[0m");
And, even more basic, a hand-crafted text file:
Both of which which correctly do the expected thing: Print a teal-colored string "TEST":
Only the test.exe I built with csc prints something else. Why?
Your program needs to be compiled for /platform:x64
if you use the AnsiCon x64 environment and with /platform:x86
if you use the AnsiCon x86/32 bits version. The exact reason is a mystery...
Originally I thought you need all this:
You need to grab the StandardOutput and let the Console.WriteLine believe you write to a File instead of to a Console and use an ASCII encoding.
This is how it will work:
var stdout = Console.OpenStandardOutput();
var con = new StreamWriter(stdout, Encoding.ASCII);
con.AutoFlush = true;
Console.SetOut(con);
Console.WriteLine("x1b[36mTESTx1b[0m");
The .Net Console.WriteLine uses an internal __ConsoleStream
that checks if the Console.Out
is as file handle or a console handle. By default it uses a console handle and therefor writes to the console by calling WriteConsoleW. In the remarks you 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 the bytes directly to the console without WriteConsoleW
interfering a simple filehandle/stream will do which is achieved by calling OpenStandardOutput
. By wrapping that stream in a StreamWriter
so we can set it again with Console.SetOut
we are done. The byte sequences are send to the OutputStream and picked up by AnsiCon.
Do notice that this is only useable with an applicable terminal emulator, like AnsiCon, as shown here:
这篇关于使用 .NET 的 ANSI 着色控制台输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!