Home >Backend Development >C++ >How to Build a System Tray Application in .NET Windows Forms?
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>
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!