Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...