在ProgressBar上显示文字

using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;

namespace MyProgressBar
{
    class ProgressBarEx: ProgressBar
    {
        [Browsable(true), Category("Appearance"), Description("需要在进度条上显示的文字")]
        public new string Text { get; set; }
        [Browsable(true), Category("Appearance"), Description("是否在进度条上显示文字")]
        public bool ShowText { get; set; }
        [Browsable(true), Category("Appearance"), Description("进度条上的文字的字体")]
        public new Font Font { get; set; }
        [Browsable(true), Category("Appearance"), Description("进度条上的文字的颜色")]
        protected Color fontColor;
        protected Brush brush;
        public Color FontColor { get { return fontColor; } set { fontColor = value; brush = new SolidBrush(value); } }

        public ProgressBarEx()
            : base()
        {
            ShowText = false;
            Font = new Font("宋体", 9, FontStyle.Regular);
            FontColor = Color.Black;
        }

        protected void DrawText()
        {
            string temp =Text;
            if (string.IsNullOrEmpty(temp))
                if(Value!=0)
                    temp = Value + "%";

            SizeF size = TextRenderer.MeasureText(temp, Font);
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;
            this.CreateGraphics().DrawString(temp, Font, brush, this.Size.Width / 2, (this.Size.Height - size.Height) / 2, sf);
        }

        protected override void WndProc(ref System.Windows.Forms.Message m)
        {
            base.WndProc(ref m);
            if (ShowText)
            { DrawText(); }
        }
    }
}

不知道为何不能在WndProc中使用switch(m.Msg) case: WM_PAINT 来完成重绘,另外重载的OnPaint事件处理函数总是不能执行。由于对WndProc不了解,只能用这种暴力的方式了。

而且对于Font和Color的默认值设置也不能成功,在网上找了一下用DefaultValue(typeof(Font),"宋体;9pt;style=Regular"),这种方法不能成功,后来只能退而求其次,放入构造函数中。

附上截图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值