Skip to content

Instantly share code, notes, and snippets.

@davidwhitney
Created April 30, 2018 10:43
Show Gist options
  • Save davidwhitney/93769e498031fa6a1ee6223c5ca8d7cf to your computer and use it in GitHub Desktop.
Save davidwhitney/93769e498031fa6a1ee6223c5ca8d7cf to your computer and use it in GitHub Desktop.
class Program
{
static void Main(string[] args)
{
var spinner = new Spinner();
spinner.Start(0, 0);
Console.WriteLine("Hello World!" + Console.BufferHeight);
Console.WriteLine("Hello World!" + Console.BufferHeight);
Console.WriteLine("Hello World!" + Console.BufferHeight);
while (true)
{
spinner.Message = Console.ReadLine();
}
//spinner.Stop();
Console.WriteLine("Spinning should have stopped now.");
Console.ReadLine();
}
}
public class Spinner
{
private readonly string _frames;
private readonly SpinnerLocation _location;
private CancellationTokenSource _cancellationTokenSource;
public string Message { get; set; }
public Spinner(string frames = @"/-\|", SpinnerLocation? location = null)
{
_frames = frames;
_location = location ?? SpinnerLocation.TopLeft;
}
public void Start(int x, int y, string message = null)
{
Message = message ?? "";
_cancellationTokenSource = new CancellationTokenSource();
var token = _cancellationTokenSource.Token;
var task = new Task(() =>
{
var counter = 0;
while (!token.IsCancellationRequested)
{
var index = ++counter % _frames.Length;
var value = _frames[index].ToString();
var initialBackground = Console.BackgroundColor;
var initialForeground = Console.ForegroundColor;
var initialLeft = Console.CursorLeft;
var initialTop = Console.CursorTop;
lock (Console.Out)
{
Console.SetCursorPosition(x, y);
Console.BackgroundColor = ConsoleColor.Gray;
Console.ForegroundColor = ConsoleColor.Black;
value += (Message ?? "").PadLeft(2);
Console.Write(value);
if (_location == SpinnerLocation.TopLeft)
{
var width = Console.BufferWidth;
var padding = string.Join("", Enumerable.Repeat(' ', width - value.Length));
Console.Write(padding);
}
Console.BackgroundColor = initialBackground;
Console.ForegroundColor = initialForeground;
Console.SetCursorPosition(initialLeft, initialTop);
}
Thread.Sleep(1000 / _frames.Length);
}
});
task.Start();
}
public void Stop()
{
_cancellationTokenSource?.Cancel();
}
public enum SpinnerLocation
{
TopLeft,
LineLeft,
LineRight
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment