Click here to Skip to main content
15,887,867 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In a C# Console application, I want to display some texts at the same position. While I can use the Console.SetCursorPosition() method to set the position, I have no idea that how can I clear the previously displayed text after that position(all text, or partial text within an area with a given width and height after that position). Can you help me?

Thanks a lot.
Posted
Updated 3-Apr-10 2:58am
v6

Existing text can be erased by overwriting with space characters.

To clear one line the sequence would be
SetCursor ROW, COLUMN
Write space * LINEWIDTH

and that can easily be extended to clear a rectangular area by incrementing the ROW value within a loop.

If it also possible to move the cursor one place to the left by writing a backspace character. The sequence backspace space backspace will erase the character to the left of the cursor.

The following polling loop demonstrates a simple way to write repeatedly to the the same location.
C#
private void ShowProgress() {
  String percent = "";
  for(Int32 i = 0; i <= 100, i++) {
    percent = String.Format(" Progress: {0}%", i);
    Console.Write(percent);
    Thread.Sleep(500);
    for (Int32 j = 0; i < percent.Length; i++) {
      Console.Write("\b \b"); // backspace - space - backspace
    }
  }
  Console.WriteLine();
}


Alan.
 
Share this answer
 
I guess Console.Clear is not what you are looking for?
 
Share this answer
 
To Mark Nischalke:


Yes.
 
Share this answer
 
You may want to take a look at Console.MoveBufferArea

I found it very convenient a while back to format some text on the console. If you simply print out the new text, then copy the entire block (plus enough white space, or err black space) to the where you need it.

For example:
int top = Console.CursorTop;
Console.Write( whatever );
//Assuming the caret is at column 0
Console.MoveBufferArea(0, top, width of block, height of block,targetLeft, targetTop);


It will however only copy a square block, so you may want to make sure you print out any stuff on a new line before copying it or you might miss bits off.

Alternatively you could just use SetCursorPosition and print out your text, but you will probably have to pad it with a lot of spaces to cover up any previous text, but I think copying an entire block including the blank space is easier.
 
Share this answer
 
To SK Genius


Thank you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900