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

2019-01-01 09:43发布

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?

15条回答
孤独总比滥情好
2楼-- · 2019-01-01 10:23

Here's another one :D

class Program
{
    static void Main(string[] args)
    {
        Console.Write("Working... ");
        int spinIndex = 0;
        while (true)
        {
            // obfuscate FTW! Let's hope overflow is disabled or testers are impatient
            Console.Write("\b" + @"/-\|"[(spinIndex++) & 3]);
        }
    }
}
查看更多
情到深处是孤独
3楼-- · 2019-01-01 10:24

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.

查看更多
心情的温度
4楼-- · 2019-01-01 10:26

\r is used for this scenarios.
\r represents a carriage return which means the cursor returns to the start of the line.
That's why windows uses \n\r as it's new line marker.
\n moves you down a line, and \r returns you to the start of the line.

查看更多
登录 后发表回答