代码之家  ›  专栏  ›  技术社区  ›  nonsensation

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

  •  4
  • nonsensation  · 技术社区  · 7 年前

    我在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位),但该应用程序将来将打印数百万行。

    有解决办法吗?

    1 回复  |  直到 7 年前
        1
  •  5
  •   Kevin Gosse    7 年前

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