C#重绘的ProcessBar

同事给的一个自定义控件的样式.

想转载过来保存一下,留存备用. 是一个自定义控件的.cs的代码文件,也不知道原文需要链接到哪里.

主要实现了ProcessBar的重绘 .

代码的主要部分就是重写了WndProc , 根据收到的windows消息判别,发生进度条变动的时候 , 使用GDI+进行进度条样式的绘制. 当然也不会漏掉调用基类base.wndproc ,不然整个控件都废了.其它的就是两个属性,也没啥别的了 .

[ToolboxItem(true)]
public class CustomProgressBar : ProgressBar
{
    // Fields
    private Color _TextColor = Color.Black;
    private Font _TextFont = new Font("SimSun ", 12f);
    private IContainer components = null;

    // Methods
    protected override void Dispose(bool disposing)
    {
        if (disposing && (this.components != null))
        {
            this.components.Dispose();
        }
        base.Dispose(disposing);
    }

    [DllImport("user32.dll ")]
    private static extern IntPtr GetWindowDC(IntPtr hWnd);
    private void InitializeComponent()
    {
        this.components = new Container();
    }

    [DllImport("user32.dll ")]
    private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        if ((m.Msg == 15) || (m.Msg == 0x133))
        {
            IntPtr windowDC = GetWindowDC(m.HWnd);
            if (windowDC.ToInt32() != 0)
            {
                Graphics graphics = Graphics.FromHdc(windowDC);
                SolidBrush brush = new SolidBrush(this._TextColor);
                string text = $"{(base.Value * 100) / base.Maximum}%";
                SizeF ef = graphics.MeasureString(text, this._TextFont);
                float x = (base.Width - ef.Width) / 2f;
                float y = (base.Height - ef.Height) / 2f;
                graphics.DrawString(text, this._TextFont, brush, x, y);
                m.Result = IntPtr.Zero;
                ReleaseDC(m.HWnd, windowDC);
            }
        }
    }

    // Properties
    public Color TextColor
    {
        get => 
            this._TextColor;
        set
        {
            this._TextColor = value;
            base.Invalidate();
        }
    }

    public Font TextFont
    {
        get => 
            this._TextFont;
        set
        {
            this._TextFont = value;
            base.Invalidate();
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值