How to drawn my own progressbar on winforms?

2019-01-27 04:52发布

问题:

Yoyo experts! I have several progressbars on my Windowsform (NOT WPF), and I would like to use different colors for each one. How can I do this? I've googled , and found that I have to create my own control. But I have no clue , how to do this. Any idea? For example progressBar1 green, progressbar2 red.

Edit: ohh, I would like to solve this, without removing the Application.EnableVisualStyles(); line, because it will screw my form looking up :/

回答1:

Yes, create your own. A rough draft to get you 80% there, embellish as needed:

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

class MyProgressBar : Control {
    public MyProgressBar() {
        this.SetStyle(ControlStyles.ResizeRedraw, true);
        this.SetStyle(ControlStyles.Selectable, false);
        Maximum = 100;
        this.ForeColor = Color.Red;
        this.BackColor = Color.White;
    }
    public decimal Minimum { get; set; }  // fix: call Invalidate in setter
    public decimal Maximum { get; set; }  // fix as above

    private decimal mValue;
    public decimal Value {
        get { return mValue; }
        set { mValue = value; Invalidate(); }
    }

    protected override void OnPaint(PaintEventArgs e) {
        var rc = new RectangleF(0, 0, (float)(this.Width * (Value - Minimum) / Maximum), this.Height);
        using (var br = new SolidBrush(this.ForeColor)) {
            e.Graphics.FillRectangle(br, rc);
        }
        base.OnPaint(e);
    }
}