我正在尝试向Tool Strip Progress Bar添加一些文字,但到目前为止我还没有成功,这里是我找到的一些代码HERE:
private void pbPrecentage(ToolStripProgressBar pb)
{
ProgressBar p = new ProgressBar();
int percent = (int)(((double)(pb.Value - pb.Minimum) /
(double)(pb.Maximum - pb.Minimum)) * 100);
using (Graphics gr = pb.CreateGraphics())
{
gr.DrawString(percent.ToString() + "%",
SystemFonts.DefaultFont,
Brushes.Black,
new PointF(pb.Width / 2 - (gr.MeasureString(percent.ToString() + "%",
SystemFonts.DefaultFont).Width / 2.0F),
pb.Height / 2 - (gr.MeasureString(percent.ToString() + "%",
SystemFonts.DefaultFont).Height / 2.0F)));
}
}
问题是Tool Strip Progress Bar没有CreateGraphics方法。所以我想知道是否有人能够成功地将文本添加到工具条进度条。
好吧,似乎ToolStripProgressBar有一个进度条属性,而该属性又有CreateGraphics方法,但现在的问题是文本值闪烁并闪烁,我该如何修复它?以下是修订后的代码:
private void pbPrecentage(ToolStripProgressBar pb)
{
int percent = (int)(((double)(pb.Value - pb.Minimum) /
(double)(pb.Maximum - pb.Minimum)) * 100);
using (Graphics gr = pb.ProgressBar.CreateGraphics())
{
gr.DrawString(percent.ToString() + "%",
SystemFonts.DefaultFont,
Brushes.Black,
new PointF(pb.Width / 2 - (gr.MeasureString(percent.ToString() + "%",
SystemFonts.DefaultFont).Width / 2.0F),
pb.Height / 2 - (gr.MeasureString(percent.ToString() + "%",
SystemFonts.DefaultFont).Height / 2.0F)));
}
}
答案 0 :(得分:6)
您遇到了一个关于Windows Forms的非常常见的问题,它基于GDI +。用于绘制控件(以及用户绘图上下文,如图形)的双缓冲的标准设置已关闭。所以只需在表单中添加一些代码:
public Form1()
{
//Activate Double Buffering for all kind of drawing within your form
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);
}
如果你想获得更好的图形,那么你也应该使用SmoothingMode作为你的绘图环境:
private void pbPrecentage(ToolStripProgressBar pb)
{
int percent = (int)(((double)(pb.Value - pb.Minimum) /
(double)(pb.Maximum - pb.Minimum)) * 100);
using (Graphics gr = pb.ProgressBar.CreateGraphics())
{
//Switch to Antialiased drawing for better (smoother) graphic results
gr.SmoothingMode = SmoothingMode.AntiAlias;
gr.DrawString(percent.ToString() + "%",
SystemFonts.DefaultFont,
Brushes.Black,
new PointF(pb.Width / 2 - (gr.MeasureString(percent.ToString() + "%",
SystemFonts.DefaultFont).Width / 2.0F),
pb.Height / 2 - (gr.MeasureString(percent.ToString() + "%",
SystemFonts.DefaultFont).Height / 2.0F)));
}
}
答案 1 :(得分:0)
在绘制更新的进度条时,我需要使用MethodInvoker来解决问题。
这是使用计时器调用的updateProgressBars()函数。
private void updateProgressBars(object sender, System.Timers.ElapsedEventArgs e)
{
this.Invoke(new MethodInvoker(delegate
{
FillDiskRatio(false);
}));
}
FillDiskRatio()更新进度条的比率。