Keep Console.ReadLine always on last line

后端 未结 3 1644
别跟我提以往
别跟我提以往 2021-01-23 03:44

I have an application written in C# which takes continuously commands from the user via a while(true) loop and Console.ReadLine.

I also do have various background operat

3条回答
  •  半阙折子戏
    2021-01-23 04:21

    Just an idea. You can use the Console.CursorTop and Console.CursorLeft properties.

    class Program
    {
        static void Main(string[] args)
        {
            new Messager(1000 * 2.5f);
            new Messager(1000 * 3);
    
            while (true)
            {
                Console.CursorTop = 0;
                Console.ReadLine();
            }
        }
    }
    
    public class Messager
    {
        Timer Timer;
    
        static int position = 1;
    
        public Messager(double interval)
        {
            this.Timer = new Timer(interval);
    
            this.Timer.Elapsed += (sender, e) =>
            {
                lock (this)
                {
                    var cursorLeft = Console.CursorLeft;
                    Console.CursorLeft = 0;
                    Console.CursorTop = position++;
                    Console.WriteLine("message from " + this.Timer.Interval);
                    Console.CursorTop = 0;
                    Console.CursorLeft = cursorLeft;
                }
            };
    
            this.Timer.Start();
        }
    }
    

提交回复
热议问题