Home >Backend Development >C++ >How to Create a Minimal System Tray Application in .NET Windows Forms?

How to Create a Minimal System Tray Application in .NET Windows Forms?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-14 18:11:44120browse

How to Create a Minimal System Tray Application in .NET Windows Forms?

Building a .NET Windows Forms System Tray Minimized Application

Unlike traditional applications that can be minimized to the system tray, Windows Forms applications that reside solely in the system tray require a different approach. This article is intended to guide you through the steps of building such a minimal application.

Solution:

The key to this type of application is to override the default Application.Run() method, which starts the standard application loop. Instead, you will create a custom class that inherits from the ApplicationContext class. In the ApplicationContext's constructor, you initialize the NotifyIcon instance, which represents the icon in the system tray and handle its behavior.

Code:

Here is an example of the code you need to implement:

<code class="language-csharp">static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Application.Run(new MyCustomApplicationContext());
    }
}

public class MyCustomApplicationContext : ApplicationContext
{
    private NotifyIcon trayIcon;

    public MyCustomApplicationContext()
    {
        // 初始化托盘图标
        trayIcon = new NotifyIcon()
        {
            Icon = Resources.AppIcon,
            ContextMenu = new ContextMenu(new MenuItem[] {
                new MenuItem("退出", Exit)
            }),
            Visible = true
        };
    }

    void Exit(object sender, EventArgs e)
    {
        // 隐藏托盘图标,否则它将一直显示到用户将鼠标悬停在其上
        trayIcon.Visible = false;

        Application.Exit();
    }
}</code>

This code creates an application that exists only in the system tray, with an icon, tooltip, and a right-click menu option to exit the application.

The above is the detailed content of How to Create a Minimal System Tray Application in .NET Windows Forms?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn