Introduction
Quite often, people find themselves writing small applications that live mainly in the TaskTray as a TaskTray icon. Something that monitors something, updates something, little applications that run in the background but that they want to let the user know it's running.
To date, the method I've seen all around the Internet to achieve this is to create the configuration form (which in turn contains the NotifyIcon
) and then hide the configuration form.
This, however, has several drawbacks, the main one being that the configuration form will flicker whenever you start the application. Getting it to start hidden can be a bit of a chore.
Fortunately, there is a better way to start an application as a NotifyIcon
: using ApplicationContext
.
Using the Code
Start by creating a WinForms project and editing the configuration form to suit your needs. Once you have done this, open up Program.cs. You should find that the last line looks like this:
Application.Run(new Form1());
This tells the Application
to load and show Form1
, and to keep the Application
alive as long as Form1
is alive. But take a look at the overloads for Run
. Not only does it accept Form
s, but also ApplicationContext
s.
Create a new class that inherits from ApplicationContext
(we will refer to it as MyApplicationContext
). Then replace the above line with:
Application.Run(new MyApplicationContext());
Inside the constructor for MyApplicationContex
, you can insert the code to initialize the NotifyIcon
. Mine looks something like this:
MenuItem configMenuItem = new MenuItem("Configuration", new EventHandler(ShowConfig));
MenuItem exitMenuItem = new MenuItem("Exit", new EventHandler(Exit));
NotifyIcon notifyIcon = new NotifyIcon();
notifyIcon.Icon = TaskTrayApplication.Properties.Resources.AppIcon;
notifyIcon.ContextMenu = new ContextMenu(new MenuItem[]
{ configMenuItem, exitMenuItem });
notifyIcon.Visible = true;
You can then create a ShowConfig
method to display the configuration window. Mine looks something like this:
Configuration configWindow = new Configuration();
void ShowConfig(object sender, EventArgs e)
{
if (configWindow.Visible)
{
configWindow.Activate();
}
else
{
configWindow.ShowDialog();
}
}
And for completeness, my Exit
method looks like this:
void Exit(object sender, EventArgs e)
{
notifyIcon.Visible = false;
Application.Exit();
}
So you should now be able to create applications that start, live and die in the TaskTray without having to hack together a form to host the NotifyIcon
.
History
- 07/05/2007
- 09/23/2007
- Fixed formatting
- Changed
configWindow.Focus();
to configWindow.Activate();