编程语言
首页 > 编程语言> > c# – 控制台:超出缓冲区时背景颜色填充行

c# – 控制台:超出缓冲区时背景颜色填充行

作者:互联网

我正在以不同的颜色打印到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();
}

enter image description here

我已经将缓冲区设置为其最大缓冲区大小(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();
}

标签:c,console,command-prompt
来源: https://codeday.me/bug/20190622/1263198.html