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

前端 未结 17 1338
南旧
南旧 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: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);
            }
        }
    

提交回复
热议问题