Can Console.Clear() Be Used to Selectively Clear Lines Instead of the Entire Console?
In a programming scenario where you wish to display answers without repeating questions, you may wonder if Console.Clear() can selectively remove only specific lines.
Solution
While Console.Clear() generally clears the entire console window, the Console.SetCursorPosition method provides a solution. This method allows you to move the cursor to a desired position within the console. By implementing this technique, you can clear specific lines without affecting the rest of the console.
Implementation
Use Console.SetCursorPosition to Position the Cursor:
Clear the Line:
Move the Cursor Back to the Original Position:
Example Code
public static void ClearCurrentConsoleLine() { int currentLineCursor = Console.CursorTop; Console.SetCursorPosition(0, Console.CursorTop); Console.Write(new string(' ', Console.WindowWidth)); // Write white spaces to overwrite the line Console.SetCursorPosition(0, currentLineCursor); // Move cursor back to original position }
Usage
Invoke the ClearCurrentConsoleLine() method to clear specific lines as needed.
Additional Information
The above is the detailed content of Can I Selectively Clear Console Lines Using C#?. For more information, please follow other related articles on the PHP Chinese website!