这就是我在栏上显示字符串的原因:
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无济于事。还有其他想法吗?也许我需要在不同的消息或不同的图形上绘制文本?