您可以使用Console.WindowLeft
/ Console.WindowTop
/ Console.WindowHeight
/ Console.WindowWidth
msdn https://learn.microsoft.com/en-us/dotnet/api/system.console.windowheight?view=net-6.0获取屏幕缓冲区当前可见区域的大小。
然后,您只需将每个字符替换为空格,就像您链接演示的答案一样。
e.g.:
public static void ClearVisibleRegion()
{
int cursorTop = Console.CursorTop;
int cursorLeft = Console.CursorLeft;
for(int y = Console.WindowTop; y < Console.WindowTop + Console.WindowHeight; y++) {
Console.SetCursorPosition(Console.WindowLeft, y);
Console.Write(new string(' ', Console.WindowWidth);
}
Console.SetCursorPosition(cursorLeft, cursorTop);
}
这将清除屏幕上当前可见的所有内容并将光标返回到其原始位置。
如果您希望光标移动到左上角,可以执行以下操作:
Console.SetCursorPosition(Console.WindowLeft, Console.WindowTop);
但这可能仍然会导致闪烁,因为清除所有线条需要一些时间。
如果您想完全避免闪烁,唯一的方法是绘制您想要在屏幕外显示的任何内容,然后立即复制到整个屏幕。这将完全消除任何闪烁。
您可以通过调用来完成此操作SetCursorPosition()
职位不在你的范围内WindowLeft
/ WindowTop
/ WindowHeight
/ WindowWidth
矩形(但仍在BufferHeight
/ BufferWidth
).
然后绘制整个窗口的内容。
然后打电话Console.MoveBufferArea() https://learn.microsoft.com/en-us/dotnet/api/system.console.movebufferarea?view=net-6.0将内容复制到当前窗口区域。