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

前端 未结 17 1027
南旧
南旧 2020-11-22 14: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 sho

相关标签:
17条回答
  • 2020-11-22 15:10

    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.

    0 讨论(0)
  • 2020-11-22 15:11

    This works if you want to make generating files look cool .

                    int num = 1;
                    var spin = new ConsoleSpinner();
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write("");
                    while (true)
                    {
                        spin.Turn();
                        Console.Write("\r{0} Generating Files ", num);
                        num++;
                    }
    

    And this is the method that i got from some answer below and modified it

    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;
                    case 4: Console.Write("\r"); break;
                }
                Thread.Sleep(100);
                Console.SetCursorPosition(23, Console.CursorTop);
            }
        }
    
    0 讨论(0)
  • 2020-11-22 15:15

    I was doing a search for this to see if the solution I wrote could be optimised for speed. What I wanted was a countdown timer, not just updating the current line. Here's what I came up with. Might be useful to someone

                int sleepTime = 5 * 60;    // 5 minutes
    
                for (int secondsRemaining = sleepTime; secondsRemaining > 0; secondsRemaining --)
                {
                    double minutesPrecise = secondsRemaining / 60;
                    double minutesRounded = Math.Round(minutesPrecise, 0);
                    int seconds = Convert.ToInt32((minutesRounded * 60) - secondsRemaining);
                    Console.Write($"\rProcess will resume in {minutesRounded}:{String.Format("{0:D2}", -seconds)} ");
                    Thread.Sleep(1000);
                }
                Console.WriteLine("");
    
    0 讨论(0)
  • 2020-11-22 15:19

    Explicitly using a Carrage Return (\r) at the beginning of the line rather than (implicitly or explicitly) using a New Line (\n) at the end should get what you want. For example:

    void demoPercentDone() {
        for(int i = 0; i < 100; i++) {
            System.Console.Write( "\rProcessing {0}%...", i );
            System.Threading.Thread.Sleep( 1000 );
        }
        System.Console.WriteLine();    
    }
    
    0 讨论(0)
  • 2020-11-22 15:21

    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]);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 15:22

    You can use the \b (backspace) escape sequence to backup a particular number of characters on the current line. This just moves the current location, it does not remove the characters.

    For example:

    string line="";
    
    for(int i=0; i<100; i++)
    {
        string backup=new string('\b',line.Length);
        Console.Write(backup);
        line=string.Format("{0}%",i);
        Console.Write(line);
    }
    

    Here, line is the percentage line to write to the console. The trick is to generate the correct number of \b characters for the previous output.

    The advantage of this over the \r approach is that if works even if your percentage output is not at the beginning of the line.

    0 讨论(0)
提交回复
热议问题