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!

 1using System;
 2using System.Threading;
 3
 4namespace PrintOnTheSpot
 5{
 6    class Program
 7    {
 8        static void Main(string[] args)
 9        {
10            int origRow = Console.CursorTop; 
11            int origCol = Console.CursorLeft;
12            Console.CursorVisible = false;
13
14            char[] spinner = { '|', '/', '-', '\\'};
15            int loop = 0;
16
17            Console.WriteLine("Press any key to exit...");
18            while (!Console.KeyAvailable)
19            {
20                loop = loop > 3 ? 0 : loop;
21                Console.SetCursorPosition(origCol, origRow+1);
22                Console.Write(spinner[loop]);
23                loop++;
24                Thread.Sleep(200);
25            }
26        }
27    }
28}
 

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

comments powered by Disqus

Related