Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Console application: How to update the display without flicker?

Tags:

console

c#-4.0

Using C# 4 in a Windows console application that continually reports progress how can I make the "redraw" of the screen more fluid?

I'd like to do one of the following: - Have it only "redraw" the part of the screen that's changing (the progress portion) and leave the rest as is. - "Redraw" the whole screen but not have it flicker.

Currently I re-write all the text (application name, etc.). Like this:

Console.Clear();
WriteTitle();
Console.WriteLine();
Console.WriteLine("Deleting:\t{0} of {1} ({2})".FormatString(count.ToString("N0"), total.ToString("N0"), (count / (decimal)total).ToString("P2")));

Which causes a lot of flickering.

like image 664
Josh M. Avatar asked Mar 25 '11 16:03

Josh M.


2 Answers

Try Console.SetCursorPosition. More details here: How can I update the current line in a C# Windows Console App?

like image 184
Thomas Li Avatar answered Oct 29 '22 03:10

Thomas Li


static void Main(string[] args)
{
    Console.SetCursorPosition(0, 0);
    Console.Write("################################");
    for (int row = 1; row < 10; row++)
    {
        Console.SetCursorPosition(0, row);
        Console.Write("#                              #");
    }
    Console.SetCursorPosition(0, 10);
    Console.Write("################################");

    int data = 1;
    System.Diagnostics.Stopwatch clock = new System.Diagnostics.Stopwatch();
    clock.Start();
    while (true)
    {
        data++;
        Console.SetCursorPosition(1, 2);
        Console.Write("Current Value: " + data.ToString());
        Console.SetCursorPosition(1, 3);
        Console.Write("Running Time: " + clock.Elapsed.TotalSeconds.ToString());
        Thread.Sleep(1000);
    }

    Console.ReadKey();
}
like image 11
CrazyDart Avatar answered Oct 29 '22 05:10

CrazyDart