控制台:超出缓冲区时背景颜色填充线

Console : background color fills line when exceeding buffer

我在 windows-console 上打印了很多不同的颜色进行测试,并随机设置了文本和背景颜色。当行超过控制台缓冲区时,背景颜色设置为整行。这是 C# 中的示例:

static void Main( String[] args )
{
    Console.BufferHeight = 16;

    foreach( var i in Enumerable.Range( 0 , Console.BufferHeight + 3 ) )
    { 
        var fgColor = Console.ForegroundColor;
        var bgColor = Console.BackgroundColor;
        var tst = i % 2 == 0;
        Console.ForegroundColor = tst ? ConsoleColor.White : ConsoleColor.Black;
        Console.BackgroundColor = tst ? ConsoleColor.Black : ConsoleColor.Yellow;
        Console.WriteLine( $"{i} HELLO WORLD" );
        Console.ForegroundColor = fgColor;
        Console.BackgroundColor = bgColor;
    }

    Console.ReadLine();
}

我已经将缓冲区设置为其最大缓冲区大小(16 位),但此应用程序将来会打印几百万行。

有解决办法吗?

I already set the buffer to its max buffer size (16 bit), but this application will print several million lines in the future.

那么我想你的意思是 Int16.MaxValue 而不是 16。

无论如何,要解决您的问题,只需恢复写入行尾字符之前的颜色:

foreach (var i in Enumerable.Range(0, Console.BufferHeight + 3))
{
    var fgColor = Console.ForegroundColor;
    var bgColor = Console.BackgroundColor;
    var tst = i % 2 == 0;
    Console.ForegroundColor = tst ? ConsoleColor.White : ConsoleColor.Black;
    Console.BackgroundColor = tst ? ConsoleColor.Black : ConsoleColor.Yellow;
    Console.Write($"{i} HELLO WORLD");
    Console.ForegroundColor = fgColor;
    Console.BackgroundColor = bgColor;
    Console.WriteLine();
}