Console.Clear()无法清除控制台回滚缓冲区,求完整清除方案
清除控制台全部内容(含回滚缓冲区)的解决方案
Console.Clear()仅清除当前控制台窗口的可见区域内容,回滚缓冲区中超出窗口高度的历史输出不会被清除。以下是几种可行的解决方法,无需开发分页器:
方法一:调用Windows原生API(仅Windows平台)
通过Win32 API直接操作控制台屏幕缓冲区,覆盖所有内容并重置属性:
using System; using System.Runtime.InteropServices; class Program { [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr GetStdHandle(int nStdHandle); [DllImport("kernel32.dll", SetLastError = true)] static extern bool GetConsoleScreenBufferInfo(IntPtr hConsoleOutput, out CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo); [DllImport("kernel32.dll", SetLastError = true)] static extern bool FillConsoleOutputCharacter(IntPtr hConsoleOutput, char cCharacter, uint nLength, COORD dwWriteCoord, out uint lpNumberOfCharsWritten); [DllImport("kernel32.dll", SetLastError = true)] static extern bool FillConsoleOutputAttribute(IntPtr hConsoleOutput, ushort wAttribute, uint nLength, COORD dwWriteCoord, out uint lpNumberOfAttrsWritten); const int STD_OUTPUT_HANDLE = -11; struct COORD { public short X; public short Y; public COORD(short X, short Y) { this.X = X; this.Y = Y; } }; struct SMALL_RECT { public short Left; public short Top; public short Right; public short Bottom; }; struct CONSOLE_SCREEN_BUFFER_INFO { public COORD dwSize; public COORD dwCursorPosition; public ushort wAttributes; public SMALL_RECT srWindow; public COORD dwMaximumWindowSize; }; public static void ClearConsole() { IntPtr hConsole = GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleScreenBufferInfo(hConsole, out CONSOLE_SCREEN_BUFFER_INFO csbi); uint screenSize = (uint)csbi.dwSize.X * (uint)csbi.dwSize.Y; COORD topLeft = new COORD(0, 0); _ = FillConsoleOutputCharacter(hConsole, ' ', screenSize, topLeft, out _); _ = FillConsoleOutputAttribute(hConsole, csbi.wAttributes, screenSize, topLeft, out _); Console.SetCursorPosition(0, 0); } static void Main(string[] args) { for (int i = 0; i < 100; i++) { Console.WriteLine(i); } ClearConsole(); Console.ReadKey(); } }
方法二:重置控制台缓冲区大小(简单快速,可能有轻微闪烁)
通过临时缩小缓冲区高度丢弃回滚内容,清除后可恢复原设置:
static void ClearAllConsoleContent() { int originalBufferHeight = Console.BufferHeight; int originalWindowHeight = Console.WindowHeight; try { Console.BufferHeight = Console.WindowHeight; Console.Clear(); Console.BufferHeight = originalBufferHeight; Console.WindowHeight = originalWindowHeight; } catch (ArgumentOutOfRangeException) { Console.Clear(); } }
方法三:跨平台解决方案(支持Windows/Linux/macOS)
利用ANSI控制序列清除全缓冲区,Windows需先启用终端ANSI支持:
static void ClearConsoleCrossPlatform() { if (OperatingSystem.IsWindows()) { // 启用Windows终端ANSI支持(Windows 10+默认已开启) Console.OutputEncoding = System.Text.Encoding.UTF8; _ = Console.WriteLine("\x1b[3J\x1b[H\x1b[2J"); } else { // Linux/macOS终端直接发送ANSI序列 Console.Write("\x1b[3J\x1b[H\x1b[2J"); } Console.SetCursorPosition(0, 0); }
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

