清除整个控制台无闪烁c#



我见过这种方法,它可以清除一行而不闪烁,但是,有没有办法对整个控制台做同样的事情?(而不是使用Console.Clear(

您可以使用Console.WindowLeft/Console.WindowTop/Console.WindowHeight/Console.WindowWidthmsdn来获取屏幕缓冲区当前可见区域的大小。

然后,您只需要将这些字符中的每一个替换为一个空格,就像您链接演示的答案一样。

例如:

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);

不过,这可能仍然会导致闪烁,因为清除所有线条需要一些时间。


如果你想完全避免闪烁,唯一的方法就是画出你想在屏幕外显示的东西,然后一次复制整个屏幕。这将完全消除任何闪烁。

您可以通过使用WindowLeft/WindowTop/WindowHeight/WindowWidthrect(但仍在BufferHeight/BufferWidth内(之外的位置调用SetCursorPosition()来实现这一点。

然后绘制整个窗口的内容。

然后调用Console.MoveBufferArea()将内容复制到当前窗口区域。

如果您可以将最新的Visual Studio与C#9一起使用。如果这是一个仅限windows的项目,我建议将一些源代码生成器与CsWin32包一起使用。

我用这个来闪电战控制台。极具表现力。

using Windows.Win32;
using Windows.Win32.System.Console;
public static void ClearConsole()
{
var rows = (short)Console.WindowHeight;
var cols = (short)Console.WindowWidth;
SafeFileHandle h = PInvoke.CreateFile("CONOUT$",
Windows.Win32.Storage.FileSystem.FILE_ACCESS_FLAGS.FILE_GENERIC_READ | Windows.Win32.Storage.FileSystem.FILE_ACCESS_FLAGS.FILE_GENERIC_WRITE,
Windows.Win32.Storage.FileSystem.FILE_SHARE_MODE.FILE_SHARE_WRITE,
null,
Windows.Win32.Storage.FileSystem.FILE_CREATION_DISPOSITION.OPEN_EXISTING,
Windows.Win32.Storage.FileSystem.FILE_FLAGS_AND_ATTRIBUTES.FILE_ATTRIBUTE_NORMAL,
null
);

if (!h.IsInvalid)
{
var screenBuffer = new CHAR_INFO[rows * cols];
var writeRegion = new SMALL_RECT
{
Left = 0,
Top = 0,
Right = (short)(cols),
Bottom = (short)(rows)
};
for (int y = 0; y < rows; y++)
{
for (int x = 0; x < cols; x++)
{
screenBuffer[y * cols + x].Attributes = (byte)Console.BackgroundColor;
//buf[y * cols + x].Char.UnicodeChar = '';
}
}
PInvoke.WriteConsoleOutput(
h,
screenBuffer[0],
new COORD { X = cols, Y = rows },
new COORD(),
ref writeRegion
);
}
}

我的NativeMethods.txt文件:

CreateFile
WriteConsoleOutput

Ofc,你不必使用这些库。现在好多了。我之前设置了我自己的pinvoke调用Kernel32.dll.

您可以使用Console.SetCursorPosition,然后覆盖您需要的一切:

public static void Main()
{
for (int i = 0; i < 100; i++)
{
Console.SetCursorPosition(0, 0);
Console.WriteLine("Index = " + i);
System.Threading.Thread.Sleep(500);
}
}

你也可以创建自己的功能来自动完成:

public static void ClearConsole()
{
Console.SetCursorPosition(0, 0);
Console.CursorVisible = false;
for (int y = 0; y<Console.WindowHeight; y++)
Console.Write(new String(' ', Console.WindowWidth));
Console.SetCursorPosition(0, 0);
Console.CursorVisible = true;
}

最新更新