无论如何要删除此自定义 ProgressBar 类中的文本闪烁? [英] Anyway to remove text flickering in this custom ProgressBar class?

查看:73
本文介绍了无论如何要删除此自定义 ProgressBar 类中的文本闪烁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在栏上显示字符串的效果:

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.DoubleBuffered 转换为 true 并没有帮助.还有其他想法吗?也许我需要在不同的消息或不同的图形上绘制文本?

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?

推荐答案

把这个 CreateParams 覆盖放在你的类中,它会解决它:

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

这篇关于无论如何要删除此自定义 ProgressBar 类中的文本闪烁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆