How can I make a .NET Windows Forms application that only runs in the System Tray?
.net, c#, system-tray, winforms
Solution
The code project article Creating a Tasktray Application gives a very simple explanation and example of creating an application that only ever exists in the System Tray.
Basically change the `Application.Run(new Form1());` line in `Program.cs` to instead start up a class that inherits from `ApplicationContext`, and have the constructor for that class initialize a `NotifyIcon`
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyCustomApplicationContext());
}
}
public class MyCustomApplicationContext : ApplicationContext
{
private NotifyIcon trayIcon;
public MyCustomApplicationContext ()
{
// Initialize Tray Icon
trayIcon = new NotifyIcon()
{
Icon = Resources.AppIcon,
ContextMenu = new ContextMenu(new MenuItem[] {
new MenuItem("Exit", Exit)
}),
Visible = true
};
}
void Exit(object sender, EventArgs e)
{
// Hide tray icon, otherwise it will remain shown until user mouses over it
trayIcon.Visible = false;
Application.Exit();
}
}
Problem
What do I need to do to make a Windows Forms application to be able to run in the System Tray? Not an application that can be minimized to the tray, but an application that will be only exist in the tray, with nothing more than - an icon - a tool tip, and - a "right click" menu.