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

non*_*ion 4 c# console command-prompt

我用不同的颜色打印到 Windows 控制台进行测试,并随机设置文本和背景颜色。当行超过控制台缓冲区时,背景颜色设置为整行。这是 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();
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

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

有解决办法吗?

Kev*_*sse 5

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

那么我认为你的意思是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();
}
Run Code Online (Sandbox Code Playgroud)