How can I update the current line in a C# Windows Console App?

When building a Windows Console App in C#, is it possible to write to the console without having to extend a current line or go to a new line? For example, if I want to show a percentage representing how close a process is to completion, I'd just like to update the value on the same line as the cursor, and not have to put each percentage on a new line.

Can this be done with a "standard" C# console app?


If you print only "r" to the console the cursor goes back to the beginning of the current line and then you can rewrite it. This should do the trick:

for(int i = 0; i < 100; ++i)
{
    Console.Write("r{0}%   ", i);
}

Notice the few spaces after the number to make sure that whatever was there before is erased.
Also notice the use of Write() instead of WriteLine() since you don't want to add an "n" at the end of the line.


You can use Console.SetCursorPosition to set the position of the cursor and then write at the current position.

Here is an example showing a simple "spinner":

static void Main(string[] args)
{
    var spin = new ConsoleSpinner();
    Console.Write("Working....");
    while (true) 
    {
        spin.Turn();
    }
}

public class ConsoleSpinner
{
    int counter;

    public void Turn()
    {
        counter++;        
        switch (counter % 4)
        {
            case 0: Console.Write("/"); counter = 0; break;
            case 1: Console.Write("-"); break;
            case 2: Console.Write(""); break;
            case 3: Console.Write("|"); break;
        }
        Thread.Sleep(100);
        Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
    }
}

Note that you will have to make sure to overwrite any existing output with new output or blanks.

Update: As it has been criticized that the example moves the cursor only back by one character, I will add this for clarification: Using SetCursorPosition you may set the cursor to any position in the console window.

Console.SetCursorPosition(0, Console.CursorTop);

will set the cursor to the beginning of the current line (or you can use Console.CursorLeft = 0 directly).


So far we have three competing alternatives for how to do this:

Console.Write("r{0}   ", value);                      // Option 1: carriage return
Console.Write("bbbbb{0}", value);                 // Option 2: backspace
{                                                      // Option 3 in two parts:
    Console.SetCursorPosition(0, Console.CursorTop);   // - Move cursor
    Console.Write(value);                              // - Rewrite
}

I've always used Console.CursorLeft = 0 , a variation on the third option, so I decided to do some tests. Here's the code I used:

public static void CursorTest()
{
    int testsize = 1000000;

    Console.WriteLine("Testing cursor position");
    Stopwatch sw = new Stopwatch();
    sw.Start();
    for (int i = 0; i < testsize; i++)
    {
        Console.Write("rCounting: {0}     ", i);
    }
    sw.Stop();
    Console.WriteLine("nTime using r: {0}", sw.ElapsedMilliseconds);

    sw.Reset();
    sw.Start();
    int top = Console.CursorTop;
    for (int i = 0; i < testsize; i++)
    {
        Console.SetCursorPosition(0, top);        
        Console.Write("Counting: {0}     ", i);
    }
    sw.Stop();
    Console.WriteLine("nTime using CursorLeft: {0}", sw.ElapsedMilliseconds);

    sw.Reset();
    sw.Start();
    Console.Write("Counting:          ");
    for (int i = 0; i < testsize; i++)
    {        
        Console.Write("bbbbbbbb{0,8}", i);
    }

    sw.Stop();
    Console.WriteLine("nTime using b: {0}", sw.ElapsedMilliseconds);
}

On my machine, I get the following results:

  • Backspaces: 25.0 seconds
  • Carriage Returns: 28.7 seconds
  • SetCursorPosition: 49.7 seconds
  • Additionally, SetCursorPosition caused noticeable flicker that I didn't observe with either of the alternatives. So, the moral is to use backspaces or carriage returns when possible , and thanks for teaching me a faster way to do this, SO!


    Update : In the comments, Joel suggests that SetCursorPosition is constant with respect to the distance moved while the other methods are linear. Further testing confirms that this is the case, however constant time and slow is still slow. In my tests, writing a long string of backspaces to the console is faster than SetCursorPosition until somewhere around 60 characters. So backspace is faster for replacing portions of the line shorter than 60 characters (or so), and it doesn't flicker, so I'm going to stand by my initial endorsement of b over r and SetCursorPosition .

    链接地址: http://www.djcxy.com/p/50568.html

    上一篇: 控制台应用程序中的.NET Global异常处理

    下一篇: 我如何更新C#Windows控制台应用程序中的当前行?