This question already has an answer here:
I have a console application and I want to create a countdown timer. This is what I have tried:
static void Main(string[] args)
{
for (int a = 10; a >= 0; a--)
{
Console.Write("Generating Preview in {0}", a);
System.Threading.Thread.Sleep(1000);
Console.Clear();
}
}
This code works in some situations. However, the problem is that it clears the entire console window and cannot be used when there are some characters above the timer.
If you print
"\r"
to the console the cursor goes back to the beginning of the current line, so this works:One easy trick you can use is to place a
\r
in your string to return it the cursor to the beginning of the current line:There are two ways i know of doing what you want
1) Use
Console.SetCursorPosition();
. This is applicable when you are sure of the amount of characters that will be above the timer.2) Use
Console.CursorLeft
. This is applicable in all cases.Code Examples
Console.SetCursorPosition and related is what you probably looking for. Get current position and set it again back aster every
Write
/WriteLine
call.Something like: