管理

C#托盘图标动画效果 - 开源研究系列文章

Posted on 2024-04-30 09:43  lzhdim  阅读(10665)  评论(0编辑  收藏  举报

       这次在编写一个CPU使用率的小应用,上次发布了获取CPU使用率的代码,这次研究的是托盘图标的动画效果的问题。

       托盘图标的动画效果,其实是多个图标,然后在时间内进行切换显示,形成的动画效果。这里笔者推荐两种方法:

  1、 Timer计时器方法;

  就是设置一个Timer计时器,然后更改计时器的定时时间,进行切换不同的图标。

/// <summary>
/// 图标动画显示计时器
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TimerAnimation_Tick(object sender, EventArgs e)
{
    if (icons.Length <= current) current = 0;
    this.NICPURater.Icon = icons[current];
    current = (current + 1) % icons.Length;
}

/// <summary>
/// CPU使用率获取显示计时器
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TimerCPUUseage_Tick(object sender, EventArgs e)
{
    interval = Math.Min(100, cpuUsage.NextValue());
    this.NICPURater.Text = $"CPU: {interval:f1}%";
    interval = 200.0f / (float)Math.Max(1.0f, Math.Min(20.0f, interval / 5.0f));

    this.TimerAnimation.Stop();
    this.TimerAnimation.Interval = (int)interval;
    this.TimerAnimation.Start();
}

  2、 无限循环法;

  设置一个无限循环,控制Thread,Sleep的时间进行切换。

private void Anmination()
{
    while (!_IsDone)
    {
        if (icons.Length <= current) current = 0;
        this.NICPURater.Icon = icons[current];
        current = (current + 1) % icons.Length;

        Thread.Sleep((int)interval);
    }
}

       这里介绍了两种托盘图标动画切换的方式,具体请读者自己去实践应用。

Copyright © 2000-2022 Lzhdim Technology Software All Rights Reserved