欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#控制台输出进度和百分比的实例代码

程序员文章站 2023-12-05 20:45:16
复制代码 代码如下: using system; using system.collections.generic; using system...
复制代码 代码如下:

 using system;
 using system.collections.generic;
 using system.linq;
 using system.text;

 namespace consoleapplication1
 {
     class program
     {
         static void main(string[] args)
         {
             bool isbreak = false;
             consolecolor colorback = console.backgroundcolor;
             consolecolor colorfore = console.foregroundcolor;

             //第一行信息           
             console.writeline("****** now working...******");

             //第二行绘制进度条背景           
             console.backgroundcolor = consolecolor.darkcyan;
             for (int i = 0; ++i <= 25; )
             {
                 console.write(" ");
             }
             console.writeline(" ");
             console.backgroundcolor = colorback;

             //第三行输出进度           
             console.writeline("0%");
             //第四行输出提示,按下回车可以取消当前进度           
             console.writeline("<press enter to break.>");
             //-----------------------上面绘制了一个完整的工作区域,下面开始工作

             //开始控制进度条和进度变化           
             for (int i = 0; ++i <= 100; )
             {
                 //先检查是否有按键请求,如果有,判断是否为回车键,如果是则退出循环               
                 if (console.keyavailable && system.console.readkey(true).key == consolekey.enter)
                 {
                     isbreak = true; break;
                 }
                 //绘制进度条进度                
                 console.backgroundcolor = consolecolor.yellow;//设置进度条颜色               
                 console.setcursorposition(i / 4, 1);//设置光标位置,参数为第几列和第几行               
                 console.write(" ");//移动进度条               
                 console.backgroundcolor = colorback;//恢复输出颜色               
                 //更新进度百分比,原理同上.               
                 console.foregroundcolor = consolecolor.green;
                 console.setcursorposition(0, 2);
                 console.write("{0}%", i);
                 console.foregroundcolor = colorfore;
                 //模拟实际工作中的延迟,否则进度太快               
                 system.threading.thread.sleep(100);
             }
             //工作完成,根据实际情况输出信息,而且清楚提示退出的信息           
             console.setcursorposition(0, 3);
             console.write(isbreak ? "break!!!" : "finished.");
             console.writeline(" ");
             //等待退出           
             console.readkey(true);
         }
     }
 }