WPF Application that only has a tray icon

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for WPF Application that only has a tray icon

🌟Building a WPF Application with a Tray Icon🌟

Are you a WPF newbie wondering how to create an application that starts minimized to the system tray? Look no further! In this blog post, we'll guide you through the process, addressing common issues and providing easy solutions. So, let's jump right in! 💪🖱️

The Scenario

You want to create a WPF application that periodically fetches an RSS feed and displays a toaster-popup notification when there are new feeds. You also want the application to have a main window, but hidden by default. Plus, when the user minimizes the window, it should minimize to the system tray, not the taskbar.

Getting Started

First, let's define the entry point for your application using the App.xaml file. Within this file, you'll find a StartupUri property that points to your main window. To hide the window by default, you'll need to modify a few elements in your XAML code.

Creating the Tray Icon

To display a tray icon in your application, you'll need to utilize the NotifyIcon class from the System.Windows.Forms namespace. Don't worry if you're using WPF – we can still make this work!

  1. Start by adding a reference to the System.Windows.Forms assembly in your project.

  2. Next, create an instance of the NotifyIcon class in your code-behind or view model. Let's call it trayIcon.

  3. Configure the tray icon properties, such as the icon image, tooltip text, and behavior.

using System.Windows.Forms;

...

NotifyIcon trayIcon = new NotifyIcon
{
    Icon = new System.Drawing.Icon("YourIconFile.ico"),
    Text = "YourApp",
    Visible = true
};

Handling Tray Icon Actions

Now that your tray icon is ready, let's make it interactive! We'll need to handle both left-click and right-click events to display the main window and show a context menu, respectively.

  1. To handle a left-click event, add the following code to your trayIcon instance:

trayIcon.MouseClick += (sender, args) =>
{
    if (args.Button == MouseButtons.Left)
    {
        // Show the main window
        Application.Current.MainWindow.Show();
    }
};
  1. To handle a right-click event, add the following code:

trayIcon.MouseUp += (sender, args) =>
{
    if (args.Button == MouseButtons.Right)
    {
        // Create and display a context menu
        ContextMenu contextMenu = new ContextMenu();

        // Add menu items and their click event handlers
        MenuItem menuItem1 = new MenuItem("Item 1");
        menuItem1.Click += MenuItem1_Click;
        contextMenu.MenuItems.Add(menuItem1);

        // Add more menu items if needed

        // Display the context menu
        contextMenu.Show(System.Windows.Forms.Control.MousePosition);
    }
};

// Handle menu item click event
private void MenuItem1_Click(object sender, EventArgs e)
{
    // Perform actions when menu item 1 is clicked
}

Minimizing to System Tray

To achieve the desired behavior of minimizing to the system tray instead of the taskbar, you'll need to override the OnStateChanged method of your WPF window.

  1. In your main window's code-behind or view model, override the OnStateChanged method:

protected override void OnStateChanged(EventArgs e)
{
    if (WindowState == WindowState.Minimized)
    {
        // Hide the main window
        Hide();

        // Show the tray icon
        trayIcon.Visible = true;
    }

    base.OnStateChanged(e);
}
  1. Don't forget to also handle restoring the window when the tray icon is double-clicked:

trayIcon.MouseDoubleClick += (sender, args) =>
{
    // Show the main window
    Application.Current.MainWindow.Show();

    // Restore the window state
    if (WindowState == WindowState.Minimized)
    {
        WindowState = WindowState.Normal;
    }
};

Crowning your Application

Congratulations! 🎉 You've successfully built a WPF application with a tray icon. Toaster-popups, hidden main windows, and system tray awesomeness are all at your fingertips now.

But don't stop here – the journey of learning WPF has just begun. Feel free to explore more advanced topics and customize your application further. So, go forth and create amazing things!

If you found this guide helpful, let us know in the comments below. We'd love to hear about your tray icon adventures and any challenges you faced along the way. Don't forget to share this post with your fellow developers who are also dipping their toes into WPF world. Happy coding! 😄👨‍💻

Resources:


Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my