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

前端 未结 17 1030
南旧
南旧 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:15

    I was doing a search for this to see if the solution I wrote could be optimised for speed. What I wanted was a countdown timer, not just updating the current line. Here's what I came up with. Might be useful to someone

                int sleepTime = 5 * 60;    // 5 minutes
    
                for (int secondsRemaining = sleepTime; secondsRemaining > 0; secondsRemaining --)
                {
                    double minutesPrecise = secondsRemaining / 60;
                    double minutesRounded = Math.Round(minutesPrecise, 0);
                    int seconds = Convert.ToInt32((minutesRounded * 60) - secondsRemaining);
                    Console.Write($"\rProcess will resume in {minutesRounded}:{String.Format("{0:D2}", -seconds)} ");
                    Thread.Sleep(1000);
                }
                Console.WriteLine("");
    

提交回复
热议问题