Use a NotifyIcon component to display status information in the system tray in C#

The NotifyIcon component adds an icon to the system's tray, which is typically on the left of the task bar. The component's Icon property determines the icon that it displays. Its Text property determines what it displays in its ToolTip. When you click one of the example's RadioButtons, the following code displays the appropriate icon and ToolTip.


// Set the happy status.
// Both the RadioButton and ContextMenu Item use the same event handler
private void Happy_Click(object sender, EventArgs e)
{
// Set the NotifyIcon's icon.
nicoStatus.Icon = Properties.Resources.HappySmall;

// Set the NotifyIcon's tooltip.
nicoStatus.Text = "Status: Happy";

// Set the form's icon.
this.Icon = Properties.Resources.HappyBoth;
}

// Set the sad status.
// Both the RadioButton and ContextMenu Item use the same event handler
private void Sad_Click(object sender, EventArgs e)
{
// Set the NotifyIcon's icon.
nicoStatus.Icon = Properties.Resources.SadSmall;

// Set the NotifyIcon's tooltip.
nicoStatus.Text = "Status: Sad";

// Set the form's icon.
this.Icon = Properties.Resources.SadBoth;
}

The NotifyIcon also has a ContextMenuStrip property that determines what context menu it displays if the user right-clicks on it. This program's Happy and Sad context menu items fire the same event handlers as the RadioButtons shown in the previous code so they do the same things.

The form's ShowInTaskbar property is false so the program doesn't appear in the taskbar. Instead you can use the NotifyIcon's context menu item Restore to restore the form after you minimize it. You can use this method to make a form only appear in the tray.

That menu item uses the following code to restore the form.

// Restore the form.
private void ctxRestore_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Normal;
}

The Exit menu item simply closes the form.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.