当前位置: 首页 > 工具软件 > processbar > 使用案例 >

C#重绘的ProcessBar

丌官绍元
2023-12-01

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

想转载过来保存一下,留存备用. 是一个自定义控件的.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();
        }
    }
}

 

 类似资料: