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

前端 未结 17 1050
南旧
南旧 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:05

    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).

提交回复
热议问题