WinForm 进度条显示进度百分比
参考: https://blog.csdn.net/zhuimengshizhe87/article/details/20640157
WinForm中显示进度条百分比有多种方式:
1. 添加 Label 或者 TextBox 等空间在 ProgressBar 上,然后设置前面的空间背景色为透明。但是WinForm 中不支持设置TextBox空间的背景色为透明色;
2.自定义ProgressBar,调用微软提供的 DrawString() 函数来实现设置进度百分比信息。详细代码如下:
(备注: 如果在UI线程之外更新进度条信息,需要使用委托的方式(多线程情况下必须使用))
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication4 { public partial class Form1 : Form { public Form1() { InitializeComponent(); var progressBar = new MyProgressBar() { Location = new Point(20, Bottom - 150), Size = new Size(Width - 60, 50), Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom }; this.Controls.Add(progressBar); var timer = new Timer { Interval = 150 }; timer.Tick += (s, e) => progressBar.Value = progressBar.Value % 100 + 1; timer.Start(); } private void Form1_Load(object sender, EventArgs e) { } } public class MyProgressBar : ProgressBar { public MyProgressBar() { SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true); } protected override void OnPaint(PaintEventArgs e) { Rectangle rect = ClientRectangle; Graphics g = e.Graphics; ProgressBarRenderer.DrawHorizontalBar(g, rect); rect.Inflate(-3, -3); if (Value > 0) { var clip = new Rectangle(rect.X, rect.Y, (int)((float)Value / Maximum * rect.Width), rect.Height); ProgressBarRenderer.DrawHorizontalChunks(g, clip); } string text = string.Format("{0}%", Value * 100 / Maximum); ; using (var font = new Font(FontFamily.GenericSerif, 20)) { SizeF sz = g.MeasureString(text, font); var location = new PointF(rect.Width / 2 - sz.Width / 2, rect.Height / 2 - sz.Height / 2 + 2); g.DrawString(text, font, Brushes.Red, location); } } } }
备注: 以下属性的设置可以减少窗口数据更新(重新绘制)的闪烁。
public MyProgressBar() { SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); }
ControlStyles.OptimizedDoubleBuffer 和 ControlStyles.AllPaintingInWmPaint 用于减少窗口显示的闪烁。必须配合 ControlStyles.UserPaint 为 true。