Can Console.Clear Be Used to Only Clear a Line Instead of Whole Console

Can Console.Clear be used to only clear a line instead of whole console?


Description

You can use the Console.SetCursorPosition function to go to a specific line number. Then you can use this function to clear the line:

public static void ClearCurrentConsoleLine()
{
int currentLineCursor = Console.CursorTop;
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, currentLineCursor);
}

Sample

Console.WriteLine("Test");
Console.SetCursorPosition(0, Console.CursorTop - 1);
ClearCurrentConsoleLine();

More Information

  • Console.SetCursorPosition Method

Clear a specific line in a Console application

I have decided to answer my own question because I have googled this and nobody seems to have a method.

Since there wasn't a clearLine() / ClearLine() method, I made one.

Here it is:

private static void clearLine()
{
Console.Write(new string(' ', Console.BufferWidth - Console.CursorLeft));
}

other possibilities:

private static void clearLine(int left, int top)
{

int pLeft = Console.CursorLeft;
int pTop = Console.CursorTop;

Console.setCursorPosition(left, top);
Console.Write(new string(' ', Console.BufferWidth - Console.CursorLeft));

Console.setCursorPosition(pLeft, pTop);
}

Clear whole Console Without flicker c#

You can use Console.SetCursorPosition and then override everything that you need to:

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

You can also create your own function to do it automatically:

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

Is possible to the comand Console.Clear() only clear a specific part of the console

Source Answer

Description

You can use the Console.SetCursorPosition function to go to a specific line number.
Than you can use this function to clear the line

public static void ClearCurrentConsoleLine()
{
int currentLineCursor = Console.CursorTop;
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, currentLineCursor);
}

Sample

Console.WriteLine("Test");
Console.SetCursorPosition(0, Console.CursorTop - 1);
ClearCurrentConsoleLine();

More Information

  • Console.SetCursorPosition Method

Clearing a line in the console

Simplest method would be to move to the start of the line, as you have done, and then write out a string of spaces the same length as the length of the line.

Console.Write(new String(' ', Console.BufferWidth));


Related Topics



Leave a reply



Submit