Search code examples
c#console

Is there a way to clear the entire console window?


My console application needs to clear the console to 100%. There will be many lines.

Console.Clear();

... clears only the last part of the console, as far as I can see. And it puts the caret on top position of the bottom part, pretending the console to be empty. I print many lines to the console and at some point the console needs the 100% clear functionality, because the user while scrolling up, must know when he reached the top, the first line. There should be a way because "cls" in the command window clears the entiry thing no matter how far down you came.

Example code:

for (int i = 0; i < 100; ++i)
    Console.WriteLine(i + ": I'm still here");
Console.Clear();
for (int i = 0; i < 5; ++i)
    Console.WriteLine(i + ": scroll up!");
Console.ReadKey();

Edit: I'm using the Visual Studio console. Console application with .NET Framework 4 for now. Can be changed, no restrictions.

Edit 2 Thanks to the answer I found this works best (only a blank line at the start remains):

Console.Clear();
Console.WriteLine("\x1b[2J");
Console.WriteLine("\x1b[3J");
Console.Clear();

Solution

  • As previously answered here: Console.Clear(); doesn't clean up the whole console

    Console.Clear();

    Console.WriteLine("\x1b[3J");

    This sequence removes the whole content of the console. (But it only works reliable if the clear command is called first)

    As described here: https://learn.microsoft.com/en-us/windows/console/clearing-the-screen

    • \x1b[3J - "3J only clears the scroll back."
    • \x1b[2J - "2J only clears the visible window"