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

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

Barbara Streisand
Release: 2025-01-14 18:01:43
Original
972 people have browsed it

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

Create a systray-only .NET Windows Forms application

To create a Windows Forms application that only runs in the system tray, follow the steps outlined in the Code Project article "Creating a Tray Application":

1. Modify the entry point:

Change the Application.Run(new Form1()); line in Program.cs to start a custom class that inherits from ApplicationContext.

2. Initialize NotifyIcon:

In the constructor of this custom class, initialize a NotifyIcon instance.

3. Implement right-click menu:

Add a context menu to NotifyIcon by setting its ContextMenu property.

4. Handle icon events:

Implement event handlers for any desired icon events such as clicks or tooltips.

5. Exit the application:

Create an event handler to handle the exit event and exit the application gracefully.

Here is a sample code snippet demonstrating this approach:

<code class="language-c#">static class Program
{
    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>
Copy after login

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template