MyProgressBar.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. using System.Drawing;
  2. using System.Windows.Forms;
  3. namespace 进度条显示百分比
  4. {
  5. public class MyProgressBar : ProgressBar//继承ProgressBar所有功能
  6. {
  7. public MyProgressBar()
  8. {
  9. SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
  10. }
  11. protected override void OnPaint(PaintEventArgs e)
  12. {
  13. Rectangle rect = ClientRectangle;
  14. Graphics g = e.Graphics;
  15. ProgressBarRenderer.DrawHorizontalBar(g, rect);
  16. rect.Inflate(-3, -3);
  17. if (Value > 0)
  18. {
  19. var clip = new Rectangle(rect.X, rect.Y, (int)((float)Value / Maximum * rect.Width), rect.Height);
  20. ProgressBarRenderer.DrawHorizontalChunks(g, clip);
  21. }
  22. string text = string.Format("{0}%", Value * 100 / Maximum); ;
  23. using (var font = new Font(FontFamily.GenericSerif, 9))
  24. {
  25. SizeF sz = g.MeasureString(text, font);
  26. var location = new PointF(rect.Width / 2 - sz.Width / 2, rect.Height / 2 - sz.Height / 2 + 2);
  27. g.DrawString(text, font, Brushes.Black, location);
  28. }
  29. }
  30. }
  31. }