Pregunta

This is what I made to have string displayed on the bar:

public class ProgressBarWithText : ProgressBar
{
    const int WmPaint = 15;
    SizeF TextSize;
    PointF TextPos;

    public ProgressBarWithText()
    {
        this.DoubleBuffered = true;
        this.TextChanged += ProgressBarWithText_TextChanged;
        this.SizeChanged += ProgressBarWithText_SizeChanged;
    }

    public override string Text
    {
        get { return base.Text; }
        set { base.Text = value; }
    }   

    void RecalcTextPos()
    {
        if (string.IsNullOrEmpty(base.Text))
            return;

        using (var graphics = Graphics.FromHwnd(this.Handle))
        {
            TextSize = graphics.MeasureString(base.Text, this.Font);
            TextPos.X = (this.Width / 2) - (TextSize.Width / 2);
            TextPos.Y = (this.Height / 2) - (TextSize.Height / 2);
        }
    }

    void ProgressBarWithText_SizeChanged(object sender, EventArgs e)
    {
        RecalcTextPos();
    }

    void ProgressBarWithText_TextChanged(object sender, EventArgs e)
    {
        RecalcTextPos();
    }     

    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);

        switch (m.Msg)
        {
            case WmPaint:
                using (var graphics = Graphics.FromHwnd(Handle))
                    graphics.DrawString(base.Text, base.Font, Brushes.Black, TextPos.X, TextPos.Y);

                break;
        }
    }
}

This works, but the text only is flickering. Turing this.DoubleBuffered to true doesn't helps. Any other ideas? maybe I need to draw text at different message or different Graphics?

¿Fue útil?

Solución

Place this CreateParams override in your class,it will sove it:

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams result = base.CreateParams;
                result.ExStyle |= 0x02000000; // WS_EX_COMPOSITED 
                return result;
            }
        }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top