【发布时间】:2011-11-20 03:49:44
【问题描述】:
我正在从文件中读取数据,并希望在此操作中附加一个进度条。我在 stackoverflow 上找到了以下代码 - 此代码归功于 William Daniel,9 月 20 日,stackoverflow 帖子标题为“如何在 C#.Net 3.5 中更改进度条的颜色”
class CustomProgressBar : ProgressBar
{
public CustomProgressBar()
{
this.SetStyle(ControlStyles.UserPaint, true);
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
// None... Helps control the flicker.
}
protected override void OnPaint(PaintEventArgs e)
{
const int inset = 2;
using (Image offscreenImage = new Bitmap(this.Width, this.Height))
{
using (Graphics offscreen = Graphics.FromImage(offscreenImage))
{
Rectangle rect = new Rectangle(0, 0, this.Width, this.Height);
if (ProgressBarRenderer.IsSupported)
ProgressBarRenderer.DrawHorizontalBar(offscreen, rect);
rect.Inflate(new Size(-inset, -inset)); // Deflate inner rectangle
rect.Width = (int)(rect.Width * ((double)this.Value / this.Maximum));
if (rect.Width == 0) rect.Width = 1;
LinearGradientBrush brush = new LinearGradientBrush(rect,
this.BackColor, this.ForeColor, LinearGradientMode.Vertical);
offscreen.FillRectangle(brush, inset, inset, rect.Width, rect.Height);
e.Graphics.DrawImage(offscreenImage, 0, 0);
offscreenImage.Dispose();
}
}
}
}
代码运行良好,但以下情况除外:
渐变似乎没有延伸到条的整个宽度。它在那里,但更集中在酒吧的底部附近,当我们到达酒吧的顶部时,它会很快变薄。关于如何解决此问题的任何建议?
如果我将进度条放在表单上并在表单中带有进度条的部分上方打开 Internet Explorer 窗口,则 Internet 窗口中的一些文本会渗入表单中的进度条.我不知道为什么,以及如何解决这个问题。
顺便说一句,如何估计您希望通过进度条显示的操作的长度?
任何帮助将不胜感激。谢谢。
【问题讨论】:
-
为什么不使用 Winforms 的内置进度条?
-
我想要一个平滑的渐变类型条,但不知道内置的条可以给我。
-
您无法真正估计操作的长度。你可以大胆猜测,然后交叉手指,希望没有人注意到你指示的进度与操作无关。不过,处理文件时,您可能会根据处理方式获得真正的指标。
-
我使用:int fileLines = System.IO.File.ReadAllLines(fd.FileName).Length;获取文件的大小,当我用流阅读器阅读它时更新栏。这没关系,但我想其他进程有一个通用的方法。
-
嗨@Zeos6,看看我的回答,对你有帮助:-)
标签: c# winforms user-controls