据我所知,Windows控制台应用程序(例如cmd.exe)中没有此类控制代码。有一些创造性的方法可以达到类似的结果。其中之一是如何在 Windows 命令行中用不同的颜色进行回显 https://stackoverflow.com/questions/2048509/how-to-echo-with-different-colors-in-the-windows-command-line。我出于好奇尝试了一下,效果很好。它使用了一些 jscript 魔法。对于日常使用,如果您需要转义代码格式化功能,您可能会发现 bash shell 模拟器之一更有用。 (如何在Windows上使用类Linux Shell(bash)进行开发? https://stackoverflow.com/questions/12293494/how-to-develop-in-linux-like-shell-bash-on-windows)
UPDATE:
我将一些非常快速和肮脏的东西放在一起,以演示一种使用“代码”的方法,其风格类似于您在问题中使用的风格。这可能不是“最好”的方式。但这可能会激发一个想法。
class Program
{
static void Main(string[] args)
{
@"
This is in ~r~red~~ and this is in ~b~blue~~. This is just some more text
to work it out a bit. ~g~And now a bit of green~~.
".WriteToConsole();
Console.ReadKey();
}
}
static public class StringConsoleExtensions
{
private static readonly Dictionary<string, ConsoleColor> ColorMap = new Dictionary<string, ConsoleColor>
{
{ "r", ConsoleColor.Red },
{ "b", ConsoleColor.Blue },
{ "g", ConsoleColor.Green },
{ "w", ConsoleColor.White },
};
static public void WriteToConsole(this string value)
{
var position = 0;
foreach (Match match in Regex.Matches(value, @"~(r|g|b|w)~([^~]*)~~"))
{
var leadingText = value.Substring(position, match.Index - position);
position += leadingText.Length + match.Length;
Console.Write(leadingText);
var currentColor = Console.ForegroundColor;
try
{
Console.ForegroundColor = ColorMap[match.Groups[1].Value];
Console.Write(match.Groups[2].Value);
}
finally
{
Console.ForegroundColor = currentColor;
}
}
if (position < value.Length)
{
Console.Write(value.Substring(position, value.Length - position));
}
}
}
我认为可能有一种方法可以让正则表达式捕获前导文本。但我没有太多时间去尝试。我很想看看是否有一种模式可以让正则表达式完成所有工作。