以下是能够在进度条上绘制文本的C#代码。它用于向进度条添加文本,显示剩余时间倒计时。我使用了Graphics类来绘制字符串,而不是Windows表单标签,因为当放置在进度条上时,标签背景无法设置为透明。
然而,使用这个代码时,每次更新文本时都会闪烁(这个方法在定时器中被调用,每秒钟触发一次),因此它几乎不停地闪烁,无法使用。
然而,使用这个代码时,每次更新文本时都会闪烁(这个方法在定时器中被调用,每秒钟触发一次),因此它几乎不停地闪烁,无法使用。
/// <summary>
/// Adds time remaining text into a System.Windows.Forms.ProgressBar
/// </summary>
/// <param name="target">The target progress bar to add text into</param>
/// <param name="remainingTimeText">The text to add into the progress bar.</param>
private void set_progress_bar_text( System.Windows.Forms.ProgressBar target, string remainingTimeText )
{
// Make sure we do not have a null progress bar.
if( target == null )
{
throw new ArgumentException( "Null Target" );
}
// Use the progress bar label font and size.
Font textFont = new Font( labelProgress.Font.Name, labelProgress.Font.Size );
// gr will be the graphics object we use to draw on the progress bar.
using( Graphics gr = target.CreateGraphics() )
{
gr.DrawString( remainingTimeText,
textFont,
new SolidBrush( Color.Black ), // The brush we will use to draw the string, using a black colour.
// The position on the progress bar to put the text.
new PointF(
// X location of text, to be placed at the centre of the progress bar.
progressBar.Width / 2 - ( gr.MeasureString( remainingTimeText,
textFont ).Width / 2.0F ),
// Y Location
progressBar.Height / 2 - ( gr.MeasureString( remainingTimeText,
textFont ).Height / 2.0F ) ) );
}
}
我已经尝试在该方法中设置DoubleBuffered = true
,如Stack Overflow上相关问题所建议的那样,但它并不能防止闪烁。由于文本是一个必须每秒更新一次的倒计时时钟,因此我无法减少文本更新的次数。有没有办法通过双缓冲来防止闪烁,或者还有其他潜在的解决方案?