2

我需要向使用多种颜色的控制台写入一个长字符串,但我需要它仅在所有写入完成后才进行视觉更新。通过设置 Console.ForegroundColor 可以简单地更改文本的颜色,但是有没有办法“锁定”控制台,并且只有在所有写入完成后才更新一次?在不锁定控制台的情况下实现此目的的一种方法是使用 ANSI 颜色代码,但较新的 Windows 操作系统不支持它们。仅在完成冗长的写入后才更新控制台的最佳方法是什么?

与此类似的东西:

Console.Lock() // Prevents visual updates
// multi_colored_string is StringBuilder
for (int counter = 0; counter < multi_colored_string.Length; counter++)
{
    char next_char = multi_colored_string[counter];
    if (next_char == "a")
    {
        Console.ForegroundColor = ConsoleColor.Magenta;
    }
    else if (next_char == "b")
    {
        Console.ForegroundColor = ConsoleColor.Cyan;
    }
    Console.Write(next_char);
}
Console.Unlock() // Allows console to update again, reflecting all writes
4

0 回答 0