Tom Buente
Tom Buente

Reputation: 11

Clear last line in the console - C# - BufferedWidth and WindowWidth

I am working on a small console application written in C#. I want to delete / clear the last line in the console.

My problem: The application behaves differently outside of the IDE (VS 2019).

The following code is working inside the IDE:

Console.SetCursorPosition(0, Console.CursorTop - 1);
Console.Write(new string(' ', Console.BufferWidth));
Console.SetCursorPosition(0, Console.CursorTop);

The follolloing code is working outside the IDE:

Console.SetCursorPosition(0, Console.CursorTop - 1);
Console.Write(new string(' ', Console.BufferWidth));
Console.SetCursorPosition(0, Console.CursorTop - 1);

I did some resach and found out that there are two properties regarding the problem. The first one is Console.WindowWidth and the second one is Console.BufferWidth.

Furthermore I found a solution on the internet:

Console.SetCursorPosition(0, Console.CursorTop - 1);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, Console.CursorTop - (Console.WindowWidth >= Console.BufferWidth ? 1 : 0));

-> This solution did not work for me.

I did some further investigation and realised that the cursor behaves differently. Interestingly Console.WindowWidth and the Console.BufferWidth properties where the same all the time (Found it out via

Console.WriteLine("WindowWidth = {0} BufferWidth = {1}", Console.WindowWidth, Console.BufferWidth);

I am fairly new to C# that is why I need your help. Could you explain me the difference between buffered and none buffered and also provide me with some solutions?

Thanks a LOT!!

Upvotes: 0

Views: 397

Answers (1)

Rufus L
Rufus L

Reputation: 37060

It sounds like you need to capture the cursor top before running your code, since it appears that the top is different after you write the blank line in some cases.

This should solve the problem, but if it doesn't please clarify specifically what behavior you want, and what behavior you're seeing that's not correct.

// Capture current cursor position
var cursorTop = Console.CursorTop;
var cursorLeft = Console.CursorLeft;

// Clear the previous line (above the current position)
Console.SetCursorPosition(0, cursorTop - 1);
Console.Write(new string(' ', Console.BufferWidth));

// Resume cusor at it's original position
Console.SetCursorPosition(cursorLeft, cursorTop);

Upvotes: 2

Related Questions