This document describes how to create and manage a system tray icon for a Windows Forms application.
A system tray icon (also known as a notification area icon) is a small icon displayed in the Windows notification area, usually located at the bottom-right corner of the screen. It allows users to interact with your application without needing a full window to be open.
To add a `NotifyIcon` to your form:
Once added, you can configure the `NotifyIcon` in the Properties window. Key properties include:
true to make it visible.Example of setting properties in code:
// Assuming you have a NotifyIcon component named 'notifyIcon1' on your form
// Load an icon resource (e.g., from your project's Resources)
this.notifyIcon1.Icon = new System.Drawing.Icon("path/to/your/icon.ico");
// Set the tooltip text
this.notifyIcon1.Text = "My Application";
// Make the icon visible
this.notifyIcon1.Visible = true;
// Create and assign a context menu strip (optional)
ContextMenuStrip contextMenu = new ContextMenuStrip();
contextMenu.Items.Add("Show Window");
contextMenu.Items.Add("Exit");
contextMenu.ItemClicked += NotifyIcon_ItemClicked; // Handle clicks
this.notifyIcon1.ContextMenuStrip = contextMenu;
The `NotifyIcon` component provides events to respond to user actions:
Example of handling Click and DoubleClick events:
// In your form's constructor or Load event:
this.notifyIcon1.Click += new EventHandler(NotifyIcon_Click);
this.notifyIcon1.DoubleClick += new EventHandler(NotifyIcon_DoubleClick);
// Event handler for Click
private void NotifyIcon_Click(object sender, EventArgs e)
{
// Show the main window if it's hidden, or bring it to front
if (this.WindowState == FormWindowState.Minimized)
{
this.WindowState = FormWindowState.Normal;
}
this.BringToFront();
this.Show();
}
// Event handler for DoubleClick
private void NotifyIcon_DoubleClick(object sender, EventArgs e)
{
// Often used to open the main window
if (this.WindowState == FormWindowState.Minimized)
{
this.WindowState = FormWindowState.Normal;
}
this.Activate(); // Ensure window gets focus
}
// Event handler for ContextMenuStrip clicks
private void NotifyIcon_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if (e.ClickedItem.Text == "Show Window")
{
if (this.WindowState == FormWindowState.Minimized)
{
this.WindowState = FormWindowState.Normal;
}
this.Activate();
}
else if (e.ClickedItem.Text == "Exit")
{
Application.Exit();
}
}
You can display informative pop-up messages using the `ShowBalloonTip` method.
this.notifyIcon1.ShowBalloonTip(5000, "New Notification", "You have received a new message.", ToolTipIcon.Info);
// The first argument is the timeout in milliseconds.
It's best practice to include your icon file (e.g., .ico) in your project and set its "Build Action" property to "Embedded resource" in Visual Studio. You can then access it via Properties.Resources.YourIconName.