在进度条中闪烁文本

本文关键字:闪烁 文本 | 更新日期: 2023-09-27 18:34:26

我做了一个很酷的进度条,中间有文字。这是我的代码:

private void timer2_Tick(object sender, EventArgs e)
{
    progressBar1.Increment(+1);
    int percent = progressBar1.Value;
    progressBar1
        .CreateGraphics()
        .DrawString(
            percent.ToString() + "%", 
            new Font("Arial", (float)8.25, FontStyle.Regular), 
            Brushes.Black, 
            new PointF(progressBar1.Width / 2 - 10, 
            progressBar1.Height / 2 - 7)
        );
    if (progressBar1.Value >= 99)
    {
        timer2.Stop();
        this.Close();
    }
}

出于某种原因,文本出现然后消失和其他奇怪的东西。为什么会这样,我该如何解决?

在进度条中闪烁文本

尝试将绘图代码移动到 Paint 事件中,这基本上是在修改控件的视觉对象,因此需要处理此问题而不是默认的绘制行为。

每当重新绘制控件时,都会擦除绘图。

相反,您需要设置一个标志,指示是否立即绘制文本,然后处理Paint事件,如果标志为 true,则绘制文本。

在计时器时钟周期处理程序中,切换标志并调用Invalidate()

另一种方法是创建一个UserControll并在进度条顶部使用标签,并分别使用每个标签,这可能更容易做到,几乎不需要任何额外的代码。