How can I update the current line in a C# Windows Console App?

前端 未结 17 1051
南旧
南旧 2020-11-22 14:43

When building a Windows Console App in C#, is it possible to write to the console without having to extend a current line or go to a new line? For example, if I want to sho

17条回答
  •  长发绾君心
    2020-11-22 15:26

    Here is my take on s soosh's and 0xA3's answers. It can update the console with user messages while updating the spinner and has an elapsed time indicator aswell.

    public class ConsoleSpiner : IDisposable
    {
        private static readonly string INDICATOR = "/-\\|";
        private static readonly string MASK = "\r{0} {1:c} {2}";
        int counter;
        Timer timer;
        string message;
    
        public ConsoleSpiner() {
            counter = 0;
            timer = new Timer(200);
            timer.Elapsed += TimerTick;
        }
    
        public void Start() {
            timer.Start();
        }
    
        public void Stop() {
            timer.Stop();
            counter = 0;
        }
    
        public string Message {
            get { return message; }
            set { message = value; }
        }
    
        private void TimerTick(object sender, ElapsedEventArgs e) {
            Turn();
        }
    
        private void Turn() {
            counter++;
            var elapsed = TimeSpan.FromMilliseconds(counter * 200);
            Console.Write(MASK, INDICATOR[counter % 4], elapsed, this.Message);
        }
    
        public void Dispose() {
            Stop();
            timer.Elapsed -= TimerTick;
            this.timer.Dispose();
        }
    }
    

    usage is something like this:

    class Program
    {
        static void Main(string[] args)
        {
            using (var spinner = new ConsoleSpiner())
            {
                spinner.Start();
                spinner.Message = "About to do some heavy staff :-)"
                DoWork();
                spinner.Message = "Now processing other staff".
                OtherWork();
                spinner.Stop();
            }
            Console.WriteLine("COMPLETED!!!!!\nPress any key to exit.");
    
        }
    }
    

提交回复
热议问题