Printing on the Spot in a Console

While installing something in Ubuntu from a terminal the installer printed a nice sequence of | / - \ in a single point on the console - a spinner. It is something trivial, but I didn’t know how to do it in C#. Now I do!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System;
using System.Threading;

namespace PrintOnTheSpot
{
    class Program
    {
        static void Main(string[] args)
        {
            int origRow = Console.CursorTop; 
            int origCol = Console.CursorLeft;
            Console.CursorVisible = false;

            char[] spinner = { '|', '/', '-', '\\'};
            int loop = 0;

            Console.WriteLine("Press any key to exit...");
            while (!Console.KeyAvailable)
            {
                loop = loop > 3 ? 0 : loop;
                Console.SetCursorPosition(origCol, origRow+1);
                Console.Write(spinner[loop]);
                loop++;
                Thread.Sleep(200);
            }
        }
    }
}
 

There, a little program that was a lot of fun to make.

comments powered by Disqus

Related