Clearing a line in the console

本秂侑毒 提交于 2019-12-06 03:18:01

问题


How can a line in the console be cleared in C#?

I know how to place the cursor at the beginning of a line:

Console.SetCursorPosition(0, Console.CursorTop);

回答1:


Simplest method would be to move to the start of the line, as you have done, and then write out a string of spaces the same length as the length of the line.

Console.Write(new String(' ', Console.BufferWidth));



回答2:


Once the last space of a console buffer row is used, the console cursor automatically jumps to the next line.

  1. Reset cursor back to the beginning before it reaches edge of console
  2. Erase old console output, placing cursor on next line
  3. Reset cursor back onto the line that was just cleared

    while (true)
    {
      Console.Write(".");
      if (Console.CursorLeft + 1 >= Console.BufferWidth)
      {
        Console.SetCursorPosition(0, Console.CursorTop);
        Console.Write(Enumerable.Repeat<char>(' ', Console.BufferWidth).ToArray());
        Console.SetCursorPosition(0, Console.CursorTop - 1);
      }
    
      if (Console.KeyAvailable)
        break;
    }
    



回答3:


(Combining at.toulan and Andrew's answers here.)

Simplest is, to overwrite over the last line:

Console.SetCursorPosition(0, Console.CursorTop - 1)
Console.WriteLine("new line of text");

If "new line of text" is shorter than the text that was there before, write spaces before writing your text, like Andrew says.




回答4:


After setting the cursor position, you can use backspace:

do { Console.Write("\b \b"); } while (Console.CursorLeft > 0);


来源:https://stackoverflow.com/questions/15421515/clearing-a-line-in-the-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!