Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

c# - How to drawn my own progressbar on winforms?

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 :/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...