c# console, Console.Clear problem

2020-02-09 04:27发布

问题:

I am writing a console program in C#.

Is there a way I can use a Console.Clear() to only clear certain things on the console screen?

Here's my issue:

I have a logo (I put it on screen using Console.WriteLine()) and a 2d array which I want to keep constant and clear everything below it.

回答1:

You could use a custom method to clear parts of the screen...

static void Clear(int x, int y, int width, int height)
{
    int curTop = Console.CursorTop;
    int curLeft = Console.CursorLeft;
    for (; height > 0;)
    {
        Console.SetCursorPosition(x, y + --height);
        Console.Write(new string(' ',width));
    }
    Console.SetCursorPosition(curLeft, curTop);
}


回答2:

Edit: The answer here shows how you can manipulate the console much more powerfully than I was aware. What I originally wrote still applies, and might be useful if you don't have these facilities available, perhaps in a different language.


Store the logo and the initially generated state of the array and then when you clear the console write out the saved values again, rather than using the same generation procedure.

As others have said, the console isn't designed for this kind of operation so you have to work around it.

Another option might be to write to a string or a string builder rather than to the console directly, then whenever the console needs updating, clear it's output and write your "output" string / stream to the console. This would let you perform string operations/ regexes etc. on your output text to remove / leave specific things in place.

However, this would involve a lot of console overhead as you would end up reprinting the entire output on every update.

A solution to THAT might be to keep a parallel string / stream representation of what you write to the console, then when you need to clear you can clear the string representation, clear the console, then write the string out to the console again. That way you would add only an additional-write operation to your usual write, and the major extra work would happen only when you cleared the console.

Whatever you do, writing to the console is never a fast operation, and if you are doing lots of operations where stuff is written to the console, it can be a significant drag on the performance of your application.



回答3:

Can you not clear and then re-write the logo and array? The console is not designed to be used as you describe.