且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在控制台中删除以前写的行

更新时间:2023-12-03 18:19:58

Silky 的评论是正确的答案:

Silky's comment is the right answer:

  • 设置合适的背景颜色
  • 为您希望清除的每一行循环:
    • 将光标位置设置在左侧
    • 写出一串合适宽度的空格

    例如:

    public static void ClearArea(int top, int left, int height, int width) 
    {
        ConsoleColor colorBefore = Console.BackgroundColor;
        try
        {
            Console.BackgroundColor = ConsoleColor.Black;
            string spaces = new string(' ', width);
            for (int i = 0; i < height; i++)
            {
                Console.SetCursorPosition(left, top + i);
                Console.Write(spaces);
            }
        }
        finally
        {
            Console.BackgroundColor = colorBefore;
        }
    }
    

    请注意,这将恢复背景颜色,但不会恢复之前的光标位置.

    Note that this will restore the background colour, but not the previous cursor location.