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。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM