繁体   English   中英

如何以编程方式获取 NotifyIcon.Icon 属性的值?

[英]How do I get the value of NotifyIcon.Icon property programmatically?

我知道这是一个菜鸟问题,但我正在努力学习和测试。 我自己提出的挑战之一是在系统托盘中创建一个 NotifyIcon(简单),然后单击一个按钮并根据当前图标值使图标在间隔上从绿色变为红色。 但是,当我尝试读取 NotifyIcon.Icon 的值时,它只是 (Icon)。 我希望它是我在 Properties.Resources 中的一个 ico 文件(即 Properties.Resources.icon.ico)。

using System;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Threading;

namespace TEST_NotifyIconChange
{
    public partial class MainWindow : Window
    {
        private NotifyIcon notifyIcon = new NotifyIcon();
        private ContextMenuStrip ContextMenuStrip_System_Tray = new ContextMenuStrip();
        private DispatcherTimer iconAnimationTimer = new DispatcherTimer();

        public MainWindow()
        {
            InitializeComponent();

            iconAnimationTimer.Interval = TimeSpan.FromSeconds(1);
            iconAnimationTimer.Tick += IconAnimationTimer_Tick;
            iconAnimationTimer.IsEnabled = false;

            ResetAll();
        }

        private void ResetAll()
        {
            notifyIcon.ContextMenuStrip = ContextMenuStrip_System_Tray;
            notifyIcon.Icon = Properties.Resources.icon_green;
            notifyIcon.Text = "I am just a standard icon";
            notifyIcon.Visible = true;
        }

        private void ChangeColorButton_Click(object sender, RoutedEventArgs e)
        {
            if (iconAnimationTimer.IsEnabled == false)
            {
                iconAnimationTimer.IsEnabled = true;
                iconAnimationTimer.Start();
            }
            else
            {
                iconAnimationTimer.Stop();
                iconAnimationTimer.IsEnabled = false;
            }
        }

        private void IconAnimationTimer_Tick(object sender, EventArgs e)
        {
            if (notifyIcon.Icon == Properties.Resources.icon_green)
            {
                Console.WriteLine("Changing to red");
                notifyIcon.Icon = Properties.Resources.icon_red;
            }
            else
            {
                Console.WriteLine("Changing to green");
                notifyIcon.Icon = Properties.Resources.icon_green;
            }
        }
    }
}

notifyIcon.Icon == Properties.Resources.icon_green永远不会返回true ,因为每次调用它时,它都会返回 Icon 的新实例。

您不需要跟踪分配的图标; 相反,您需要跟踪状态并根据状态分配一个图标。 要跟踪状态,您可以使用NotifyIconTag属性或Form的成员字段。 但不要将 Icon 属性视为状态指示器。

万一您有兴趣比较两个Icon对象以查看它们是否是相同的图标,您可以使用以下方法:

bool AreIconsEqual(Icon ico1, Icon ico2)
{
    byte[] bytes1, bytes2;
    using (var fs = new MemoryStream())
    {
        ico1.Save(fs);
        bytes1 = fs.ToArray();
    }
    using (var fs = new MemoryStream())
    {
        ico2.Save(fs);
        bytes2 = fs.ToArray();
    }
    return bytes1.SequenceEqual(bytes2);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM