C#如何实现彩色进度条

2025-10-12 12:48:22

1、创建一个WinForm程序,名称随便。

C#如何实现彩色进度条

2、新建一个类叫"ColorsProgressBar",代码如下:

using System;

using System.Collections.Generic;

using System.Drawing;

namespace System.Windows.Forms

{

    public class ColorsProgressBar : ProgressBar

    {

        private List<Color> colors;

        public ColorsProgressBar() : base()

        {

            base.SetStyle(ControlStyles.UserPaint, true);

            this.Minimum = 0;

            colors = new List<Color>();

            Random r = new Random();

            for (int i = 0; i < this.Maximum - this.Minimum; i++)

            {

                this.Colors.Add(Color.FromArgb(r.Next(0, 256), r.Next(0, 256), r.Next(0, 256)));

            }

        }

        public List<Color> Colors

        {

            get { return colors; }

            set

            {

                if (value.Count != this.Maximum - this.Minimum || value.Count == 0)

                {

                    throw new ArgumentException("System.Windows.Forms.ColorProgressBar.Colors.Count不等于System.Windows.Forms.ColorProgressBar.Maximum-System.Windows.Forms.ColorProgressBar.Minimum或者等于0");

                }

                colors = value;

            }

        }

        protected override void OnPaint(PaintEventArgs e)

        {

            SolidBrush brush = null;

            Pen pen = null;

            Rectangle bounds = new Rectangle(0, 0, base.Width, base.Height);

            e.Graphics.FillRectangle(new SolidBrush(this.BackColor), 1, 1, bounds.Width - 2, bounds.Height - 2);

            bounds.Height -= 4;

            bounds.Width = ((int)(bounds.Width * (((double)base.Value) / ((double)base.Maximum)))) - 4;

            for (int i = 0; i < this.Value; i++)

            {

                e.Graphics.FillRectangle(new SolidBrush(this.Colors[i]), new Rectangle((this.Width / (this.Maximum - this.Minimum)) * i, 0, this.Width / (this.Maximum - this.Minimum), this.Height));

            }

        }

    }

}

3、生成一下,再到Windows窗体拖入ColorsProgressBar和一个Button,Button上显示"启动"。

C#如何实现彩色进度条

4、给显示"启动"的Button注册点击事件,代码如下图所示:

C#如何实现彩色进度条

5、启动应用程序,点击"启动"就可以看到进度条的颜色一直在变化啦~~~

C#如何实现彩色进度条

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢