Oct 27, 2014 09:29 PM
(This post was last modified: Oct 27, 2014 09:31 PM by Delirium™.)
Hello.
I was in need of a progress bar with the ability to display the percentage on it and using a label onto a default progress bar sounded like a dumb method therefore, I wrote my own custom progress bar control with the ability to display text or percentage built-in.
Here's the source:
Nothing significant at all but could be useful to a couple of people. Enjoy.
I was in need of a progress bar with the ability to display the percentage on it and using a label onto a default progress bar sounded like a dumb method therefore, I wrote my own custom progress bar control with the ability to display text or percentage built-in.
Here's the source:
Code
using System;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public enum ProgressBarDisplayStyle
{
Percentage,
Text
}
class TextProgressBar : ProgressBar
{
[DllImport("uxtheme.dll")]
private static extern int SetWindowTheme(IntPtr hWnd, string appname, string idlist);
private ProgressBarDisplayStyle _DisplayStyle = ProgressBarDisplayStyle.Text;
[Browsable(true)]
[Category("ProgressBar Style")]
public ProgressBarDisplayStyle DisplayStyle
{
get { return _DisplayStyle; }
set
{
_DisplayStyle = value;
Invalidate();
}
}
private string _Text = null;
[Browsable(true)]
[Category("ProgressBar Style")]
public string Text
{
get { return _Text; }
set { _Text = value; Invalidate(); }
}
protected override void OnHandleCreated(EventArgs e)
{
SetWindowTheme(Handle, "", "");
base.OnHandleCreated(e);
}
public TextProgressBar()
{
SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
Text = Name;
}
protected override void OnPaint(PaintEventArgs e)
{
Rectangle R = ClientRectangle;
Graphics G = e.Graphics;
ProgressBarRenderer.DrawHorizontalBar(G, R);
if (Value > 0)
{
Rectangle R2 = new Rectangle(R.X, R.Y, (int)Math.Round(((float)Value / Maximum) * R.Width), R.Height);
ProgressBarRenderer.DrawHorizontalChunks(G, R2);
}
string ProgressText = (DisplayStyle == ProgressBarDisplayStyle.Text) ? Text : Value + "%";
Font F = new Font("Segoe UI", 10);
SizeF TextSize = G.MeasureString(ProgressText, F);
Point Center = new Point(Convert.ToInt32((Width / 2) - TextSize.Width / 2), Convert.ToInt32((Height / 2) - TextSize.Height / 2));
G.DrawString(ProgressText, F, Brushes.Black, Center);
F.Dispose();
}
}Nothing significant at all but could be useful to a couple of people. Enjoy.


