Developing a System Tray-Only .NET Windows Forms Application
Standard Windows Forms apps typically occupy space in the main window area. However, some applications only need to reside in the system tray. Here's how to create one:
1. Adjusting Application Startup:
In your Program.cs
file, replace Application.Run(new Form1());
with a call to a custom application context class inheriting from ApplicationContext
. For instance: MyCustomApplicationContext
.
<code class="language-csharp">public class MyCustomApplicationContext : ApplicationContext</code>
2. Creating and Configuring the NotifyIcon:
Within your custom application context class, create a NotifyIcon
object. Set its icon, tooltip text, and context menu. Ensure the icon is set to visible.
<code class="language-csharp">trayIcon = new NotifyIcon() { // ...icon, tooltip, context menu settings... Visible = true };</code>
3. Implementing Application Exit:
Attach an event handler to your "Exit" menu item. This handler should hide the tray icon and gracefully close the application.
<code class="language-csharp">void Exit(object sender, EventArgs e) { trayIcon.Visible = false; Application.Exit(); }</code>
4. Complete Code Example:
Here's a skeletal example demonstrating the process in Program.cs
and MyCustomApplicationContext
:
Program.cs
:
<code class="language-csharp">Application.Run(new MyCustomApplicationContext());</code>
MyCustomApplicationContext.cs
:
<code class="language-csharp">public class MyCustomApplicationContext : ApplicationContext { private NotifyIcon trayIcon; public MyCustomApplicationContext() { // ...NotifyIcon initialization... } void Exit(object sender, EventArgs e) { // ...Exit handling... } }</code>
By following these steps, your .NET Windows Forms application will operate exclusively within the system tray, offering a subtle and user-friendly interface.
The above is the detailed content of How to Build a System Tray-Only .NET Windows Forms Application?. For more information, please follow other related articles on the PHP Chinese website!