[英]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 的新實例。
您不需要跟蹤分配的圖標; 相反,您需要跟蹤狀態並根據狀態分配一個圖標。 要跟蹤狀態,您可以使用NotifyIcon
的Tag
屬性或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.