6.16 Create an Animated System Tray Icon


Problem

You need to create an animated system tray icon (perhaps to indicate the status of a long-running task).

Solution

Create and show a NotifyIcon control. Use a timer that fires periodically (every second or so) and updates the NotifyIcon.Icon property.

Discussion

The .NET Framework makes it easy to show a system tray icon with the NotifyIcon control. You simply need to add this control to a form, supply an icon by setting the Icon property, and, optionally , you can add a linked context menu through the ContextMenu property. The NotifyIcon control automatically displays its context menu when it's right-clicked, unlike most other controls.

You can animate a system tray icon by simply swapping the icon periodically. For example, the following program uses eight icons, each of which shows a moon graphic in a different stage of fullness. By moving from one image to another, the illusion of animation is created.

 using System; using System.Windows.Forms; using System.Drawing; public class AnimatedSystemTrayIcon : System.Windows.Forms.Form {     // (Designer code omitted.)     Icon[] images;     int offset = 0;     private void Form1_Load(object sender, System.EventArgs e) {              // Load the basic set of eight icons.         images = new Icon[8];         images[0] = new Icon("moon01.ico");         images[1] = new Icon("moon02.ico");         images[2] = new Icon("moon03.ico");         images[3] = new Icon("moon04.ico");         images[4] = new Icon("moon05.ico");         images[5] = new Icon("moon06.ico");         images[6] = new Icon("moon07.ico");         images[7] = new Icon("moon08.ico");     }     private void timer_Elapsed(object sender,        System.Timers.ElapsedEventArgs e) {              // Change the icon.         // This event handler fires once every second (1000 ms).         notifyIcon.Icon = images[offset];         offset++;         if (offset > 7) offset = 0;     } } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net