Created
October 7, 2020 09:51
-
-
Save Rudde/51b709894a9170b4c13cb4d99f6287c9 to your computer and use it in GitHub Desktop.
Will display a pleasant spinner in your C# console apps.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ConsoleSpinner : IDisposable | |
{ | |
private const string Sequence = @"/-\|"; | |
private int counter = 0; | |
private readonly int? left; | |
private readonly int? top; | |
private readonly int delay; | |
private bool active; | |
private readonly Thread thread; | |
private readonly ConsoleColor? color; | |
private readonly ConsoleColor originalColor; | |
public ConsoleSpinner(int? left = null, int? top = null, int delay = 100, ConsoleColor? color = null) | |
{ | |
this.left = left; | |
this.top = top; | |
this.delay = delay; | |
this.originalColor = Console.ForegroundColor; | |
this.color = color; | |
thread = new Thread(Spin); | |
} | |
public void Start() | |
{ | |
active = true; | |
if (!thread.IsAlive) | |
thread.Start(); | |
} | |
public void Stop() | |
{ | |
active = false; | |
Draw(' '); | |
} | |
private void Spin() | |
{ | |
while (active) | |
{ | |
Turn(); | |
Thread.Sleep(delay); | |
} | |
} | |
private void Draw(char c) | |
{ | |
Console.SetCursorPosition(left ?? ((Console.CursorLeft - 1) > 0 ? Console.CursorLeft - 1 : 1), top ?? Console.CursorTop); | |
if (color != null) | |
Console.ForegroundColor = (ConsoleColor)color; | |
Console.Write(c); | |
} | |
private void Turn() | |
{ | |
Draw(Sequence[++counter % Sequence.Length]); | |
} | |
public void Dispose() | |
{ | |
Stop(); | |
Console.ForegroundColor = originalColor; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment