There are a number of options available ranging from a CodePlex rewrite of the whole NotifyIcon control using the native WIN32 APIs to simply reusing the Windows Forms version of the control. I did not want to take a dependency on code that I did not have to, so in this case so I went with the Windows Forms version. It has all I need, and the implementation is really simple to boot.
This is the process I followed in my WPF app:
- Create an Icon (I use Paint.NET with this plug-in to create icons)
- Add the new icon to your project as a resource Windows Forms style .. not as a Resource build type but as EmbeddedResource (I tend to put icons in a folder with the name Resources and then use then use the Resources tab in the projects Properties).
- In the App class, override the OnStartup method, and then create your NotifyIcon instance:
private System.Windows.Forms.NotifyIcon notify;
...
this.notify = new System.Windows.Forms.NotifyIcon();
this.notify.Text = "Taskbar Compass";
this.notify.Icon = PaulJ.TaskbarCompass.Properties.Resources.Compass;
this.notify.Visible = true;
this.notify.ContextMenu = new System.Windows.Forms.ContextMenu(new System.Windows.Forms.MenuItem[]
{
new System.Windows.Forms.MenuItem("Show compass", (s, e) => this.MainWindow.Show()),
new System.Windows.Forms.MenuItem("Hide compass", (s, e) => this.MainWindow.Hide()),
new System.Windows.Forms.MenuItem("-"),
new System.Windows.Forms.MenuItem("Close", (s, e) => this.Shutdown())
});
- In the App class, over the OnExit method, and then dispose the NotifyIcon; otherwise the icon will hang around after the application is closed:
if (this.notify != null)
{
this.notify.Dispose();
}
And there you have it. I have updated the Taskbar Compass sample application (initially created in this post) to now include with a NotifyIcon, which you can download from here: TaskbarCompass.zip.
As usual if you have a comments, questions, flames, enhancements I would love to hear from you; in the meantime think deeply and enjoy.
1 comments:
Dependencies on third-party libraries are indeed worth considering. On the other hand, the WinForms implementation is somewhat limited, which is why I've put together a solution that leverages some few features of the WPF platform in order to provide some more eye candy (WPF NotifyIcon).
...I guess if had discovered your compass earlier, I could have spared me quite some headaches when it came to dealing with the tray's location :)
Cheers,
Philipp
Post a Comment