C#修改ProgressBar控件 [自定义控件修改]

我们有时候需要修改一些.NET内置控件来匹配我们项目的风格,这里以修改ProgressBar为示例,说明一下几个关键点。

目标:我们只要修改进度条的颜色(用控件的前景色);其他功能保持原控件的功能就可以了

主要内容:我们主要做的内容就是在重写OnPaint()事件,重绘进度条(用到前景色设置和进度条的Value属性)

关键点:需要用SetStyle()来把控件的模式设为UserPaint来让我们自定义绘制生效

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;


namespace NewProgressBar
{
    //继承于内置的ProgressBar,然后保持绝大多数功能而只修改部分属性
    public class NewProgressBar: System.Windows.Forms.ProgressBar
    {
        //修改属性来让自定义绘制生效
        public NProgressBar()
        {
            this.SetStyle(ControlStyles.UserPaint, true);//必须设置为UserPaint,自定义才起作用
        }
        
        //我们要做的主要就是重写OnPaint()事件
        protected override void OnPaint(PaintEventArgs e)
        {
            Rectangle rec = e.ClipRectangle;

            rec.Width = (int)(rec.Width * ((double)Value / Maximum)) - 4;
            if (ProgressBarRenderer.IsSupported)
                ProgressBarRenderer.DrawHorizontalBar(e.Graphics, e.ClipRectangle);
            rec.Height = rec.Height - 4;
            e.Graphics.FillRectangle(new SolidBrush(this.ForeColor), 2, 2, rec.Width, rec.Height);//用前景色绘制进度条进度
        }
    }
}

示例比较简单,希望给大家有一些帮助。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值