65.9K
CodeProject 正在变化。 阅读更多。
Home

进度指示器 - 可自定义

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.78/5 (6投票s)

2011年5月31日

CPOL

2分钟阅读

viewsIcon

36238

downloadIcon

2168

本文演示了一个适用于 Windows Forms 应用程序的可定制的忙碌进度指示器。

 

 

介绍 

本文演示了创建进度指示器控件,通常用于显示大量数据填充的进度。

背景

  • 关键在于创建活动和非活动图像,并适当地放置它们以使其看起来像动画。
  • 后台运行的计时器以一致的持续时间更新活动图像的位置。
  • 该控件设计为可在设计器中进行自定义,并且可以在运行时显示为模态对话框。
  • 图像通常是矩形形式,并且背景会被 BitMap.MakeTransparent 调用忽略。

Using the Code

ProgressIndicator 中图像的总数由 DotsCount 属性控制。后台运行的计时器决定绘制哪个索引为活动状态,其余索引绘制为非活动状态。

void _progressTimer_Tick(object sender, EventArgs e)
{
    this.ActiveIndex++;

    if (ActiveIndex == this.DotsCount)
        this.ActiveIndex = 0;

    this.Refresh();
}

并且在绘制事件中,绘制活动和非活动图像;每个图像将放置在根据控件和图像的宽度计算出的距离处。

while (iterator < this.DotsCount)
{
    if (iterator == this.ActiveIndex)
    {
        e.Graphics.DrawImageUnscaled(this.ActiveImage,new Point(X,Y));
    }
    else
    {
        e.Graphics.DrawImageUnscaled(this.InActiveImage,new Point(X,Y));
    }
}

默认的活动和非活动图像作为嵌入式资源添加到程序集中,并在实例化控件时填充到属性中,如下所示

Stream imgStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(
                   "Creatives.Resources.ActiveImage.png");
this._activeDot = Image.FromStream(imgStream);
(this._activeDot as Bitmap).MakeTransparent(Color.White);
            
imgStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(
                     "Creatives.Resources.InActiveImage.png");
this._inactiveDot = Image.FromStream(imgStream);
(this._inactiveDot as Bitmap).MakeTransparent(Color.White);

当调用 Show 方法时,将控件添加到 WrapperForm 并填充到其大小,然后显示为对话框窗口。

public void ShowProgressIndicator()
{
    this.WrapperForm.Controls.Add(this);
    this.WrapperForm.Size = this.Size;
    this.Dock = DockStyle.Fill;

    this.WrapperForm.ShowDialog();
}

关注点

必须取消挂钩所有事件,以避免对象被保存在内存中以避免内存泄漏,并且必须释放所有使用的非托管资源。

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        _progressTimer.Tick -= new EventHandler(_progressTimer_Tick);

        if (_wrapperForm != null)
        {
            _wrapperForm.Shown -= new EventHandler(wrapperFormShown);
        }
    }

    base.Dispose(disposing);
}

包装窗体将不会接收鼠标激活,并且始终保持在所有其他窗口之上;这是通过窗口样式完成的。

CreateParams cp = base.CreateParams;

cp.ExStyle |= /*WS_EX_TOPMOST */0x00000008 | /*WS_EX_NOACTIVATE */0x08000000;

// Take a look at this link for more window styles
// http://www.pinvoke.net/default.aspx/Enums/WindowStylesEx.html

希望这能帮助您构建丰富的用户界面。请留下您宝贵的评论和建议。

© . All rights reserved.