Is there anyway to remove flickering text in this normal ProgressBar class?

This is what I did to make the string appear in the panel:

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

      

It works, but the text only flickers. Turing this.DoubleBuffered to true doesn't help. Any other ideas? maybe i need to draw text in another post or in another Graphics ?

0


source to share


1 answer


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



        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams result = base.CreateParams;
                result.ExStyle |= 0x02000000; // WS_EX_COMPOSITED 
                return result;
            }
        }

      

+4


source







All Articles