[C#] ConsoleApp 模擬進度條應用

利用 Console.SetCursorPosition 在 ConsoleApp 下模擬進度條功能。

 圖 1 ConsoleApp 模擬進度條圖片

using System;
namespace ConsoleApplication1
{
    class Program
    {
        static int maxValue = 10000;    // 表示數值最大值
        static int factor = 2;          // 表示 ProgressBar 每格 % 數

        static void Main(string[] args)
        {
            for (int i = 0; i <= maxValue; i++)
            {
                Console.SetCursorPosition(0, 0);
                int process = (int)(((float)i / maxValue) * 100 / factor);
                Console.WriteLine(" ****** ConsoleApp ProgressBar Style 1 ... ****** ");
                ProgressBarStyle1(process);

                Console.WriteLine("\n ****** ConsoleApp ProgressBar Style 2 ... ****** ");
                ProgressBarStyle2(process);


                Console.WriteLine(string.Format("\n目前進度:{0}% ({1}/{2})", process * factor, i, maxValue));
                if (i == 5000) { Console.ReadKey(); }
            }
            Console.WriteLine("Press any key to exit ..");
            Console.ReadKey();
        }

        static void ProgressBarStyle1(int percent)
        {
            string str = "|";
            for (int i = 1; i <= percent - 1; i++)
            {
                str += "=";
            } str += ">";
            for (int i = percent; i < 100 / factor; i++)
            {
                str += " ";
            }
            Console.WriteLine(string.Format("{0}| {1}%", str, percent * factor));
        }

        static void ProgressBarStyle2(int percent)
        {
            Console.Write("|");
            for (int i = 1; i <= percent; i++)
            {
                Console.BackgroundColor = ConsoleColor.Yellow;
                Console.Write(" ");
            }
            for (int i = percent; i < 100 / factor; i++)
            {
                Console.BackgroundColor = ConsoleColor.DarkCyan;
                Console.Write(" ");
            }
            Console.BackgroundColor = ConsoleColor.Black;
            Console.Write("| ");

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine(string.Format("{0}%", percent * factor));
            Console.ForegroundColor = ConsoleColor.White; ;
        }
    }
}

留言

這個網誌中的熱門文章