In a recently explored project, wiping out the entire console screen using Console.Clear() proved effective. However, a more refined approach was desired: clearing only specific lines instead of the entire console.
Unfortunately, Console.Clear() lacks the ability to selectively target specific lines for erasure. However, you can employ the Console.SetCursorPosition function to navigate to a specific line number. Once positioned on the desired line, you can clear it by writing a series of spaces spanning the console window width, effectively overwriting the previous text.
To simplify this process, we define a static method called ClearCurrentConsoleLine():
public static void ClearCurrentConsoleLine() { int currentLineCursor = Console.CursorTop; Console.SetCursorPosition(0, Console.CursorTop); Console.Write(new string(' ', Console.WindowWidth)); Console.SetCursorPosition(0, currentLineCursor); }
This method determines the current line cursor position, sets the cursor back to the beginning of that line, writes spaces across the window width to overwrite the text, and then returns the cursor to its original position.
To illustrate this approach, consider the following example:
Console.WriteLine("Test"); Console.SetCursorPosition(0, Console.CursorTop - 1); ClearCurrentConsoleLine();
When executed, this code:
As a result, "Test" is removed from the console display, while leaving any subsequent content intact.
For further exploration, refer to the MSDN documentation for Console.SetCursorPosition:
The above is the detailed content of Can You Selectively Clear Specific Lines in the Console Using C#?. For more information, please follow other related articles on the PHP Chinese website!