using System.ComponentModel; using SolidBrush = System.Drawing.SolidBrush; namespace UI_WinForms.Components; public sealed partial class NXProgressBar : UserControl { private static readonly SolidBrush BACKGROUND_NOT_FILLED = new(SystemColors.Control); private readonly SolidBrush backgroundFilled; private readonly SolidBrush textBrush; public NXProgressBar() { this.InitializeComponent(); this.backgroundFilled = new SolidBrush(this.BackColor); this.textBrush = new SolidBrush(this.ForeColor); } [Category("Settings"), Description("Text to show inside the progress bar.")] public string InformationText { get; set; } = string.Empty; [Category("Settings"), Description("The current percentage [0,100] of the progress bar.")] public int PercentInt { get => (int) (this.PercentFloat * 100); set => this.PercentFloat = value / 100f; } [Category("Settings"), Description("The current percentage [0,1] of the progress bar.")] public float PercentFloat { get; set; } = 0; [Category("Settings"), Description("When true, appends the percentage to the text.")] public bool AppendPercentageToText { get; set; } = true; protected override void OnPaintBackground(PaintEventArgs e) { // Do not paint the background. } // Draw the progress bar by filling the background of the label with color: protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); var width = (int) MathF.Ceiling((this.Width - this.Margin.Horizontal) * this.PercentFloat); var height = this.Height - this.Margin.Vertical; // Erase the background: e.Graphics.FillRectangle(BACKGROUND_NOT_FILLED, this.Margin.Left, this.Margin.Top, this.Width - this.Margin.Horizontal, height); // Draw the filled background: e.Graphics.FillRectangle(this.backgroundFilled, this.Margin.Left, this.Margin.Top, width, height); // Calculate the text x position by using the margin: var textX = this.Margin.Left + this.Padding.Left; // Calculate the text y position by considering the margin: var textY = (int) MathF.Ceiling((this.Height - this.Font.Height) / 2f) + this.Margin.Top + this.Padding.Top; // Draw the text horizontally at the beginning, and vertically centered: e.Graphics.DrawString(this.GetTextForRendering(), this.Font, this.textBrush, textX, textY); } private string GetTextForRendering() { var text = this.InformationText; if (this.AppendPercentageToText) text += $" ({this.PercentInt}%)"; return text; } }