Console animations

前端 未结 11 1690
误落风尘
误落风尘 2020-12-04 10:15

I just want to know how to create simple animations like blinking, moving stuffs on C# console applications. Is there any special method for this?

11条回答
  •  误落风尘
    2020-12-04 10:33

    Here is my spinner. The purpose of it is to have a program do some work while the spinner displays to the user that something is actually happening:

      public class Spinner : 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;
    
         public Spinner(int left, int top, int delay = 100)
         {
            this.left = left;
            this.top = top;
            this.delay = delay;
            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, top);
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write(c);
         }
    
         private void Turn()
         {
            Draw(Sequence[++counter % Sequence.Length]);
         }
    
         public void Dispose()
         {
            Stop();
         }
      }
    

    And you use the class like this:

         var spinner = new Spinner(10, 10);
    
         spinner.Start();
    
         // Do your work here instead of sleeping...
         Thread.Sleep(10000);
    
         spinner.Stop();
    

提交回复
热议问题