[英]Changing System Tray Icon Image
我在 .Net 中構建了一個托盤應用程序,它工作正常。 但是,用戶希望在特定條件下在運行時更改托盤圖標圖像。 為了簡單起見,讓我們說,有些東西不起作用 - 托盤圖標應該顯示紅色圖像; 如果一切正常,它應該顯示綠色。 我不確定如何在 .Net 中實現這一點。
請就此提供一些意見。 謝謝
我為 Tray 構建了 CustomApplicationContent。 下面的一些片段:
程序.cs
[STAThread]
static void Main()
{
if (!SingleInstance.Start()) { return; }
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
{
var applicationContext = new CustomApplicationContext();
Application.Run(applicationContext);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Program Terminated Unexpectedly",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
SingleInstance.Stop();
}
自定義應用程序上下文.cs
public class CustomApplicationContext : ApplicationContext
{
private System.ComponentModel.IContainer components; // a list of components to dispose when the context is disposed
private NotifyIcon notifyIcon;
private static readonly string IconFileName = "green.ico";
private static readonly string DefaultTooltip = "Employee Management System";
private readonly TrayManager trayManager;
public CustomApplicationContext()
{
InitializeContext();
trayManager = new TrayManager(notifyIcon);
}
protected override void Dispose(bool disposing)
{
if (disposing && components != null) { components.Dispose(); }
}
private void InitializeContext()
{
components = new System.ComponentModel.Container();
notifyIcon = new NotifyIcon(components)
{
ContextMenuStrip = new ContextMenuStrip(),
Icon = new Icon(IconFileName),
Text = DefaultTooltip,
Visible = true
};
notifyIcon.ContextMenuStrip.Opening += ContextMenuStrip_Opening;
notifyIcon.DoubleClick += notifyIcon_DoubleClick;
//notifyIcon.MouseUp += notifyIcon_MouseUp;
}
private void notifyIcon_DoubleClick(object sender, EventArgs e)
{
ShowAboutForm();
}
private TestForm testForm;
private void ShowAboutForm()
{
if (testForm == null)
{
testForm = new TestForm { trayManager = trayManager };
testForm.Closed += testForm_Closed; ; // avoid reshowing a disposed form
testForm.Show();
}
else { testForm.Activate(); }
}
void testForm_Closed(object sender, EventArgs e)
{
testForm = null;
}
我在哪里添加計時器 - 在上下文中? 用戶可能無法打開表單,因此在表單上添加計時器可能無法始終有效。 如何更改圖標?
您可以在項目的Resource.resx文件 Red.ico 和 Green.ico 中添加 2 個圖標,並在不同情況下以這種方式使用它們:
this.notifyIcon1.Icon = Properties.Resources.Red;
或者
this.notifyIcon1.Icon = Properties.Resources.Green;
要將圖標添加到Resourse.resx
,請從項目的Properties
文件夾中打開Resources.resx
從設計器工具欄中的第一個下拉列表中,選擇Icons
,然后從下一個下拉列表中選擇Add Existing File...
並添加您的圖標文件。 您還可以在此處重命名項目。
我會讓你的 Icons Embedded Resources ,然后使用這樣的代碼在運行時更改當前顯示的:
notifyIcon.Icon = new Icon(this.GetType(), "red.ico");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.