HotDog's Blog

Hotdog (Robert Verpalen) about C# and vb.net

This blog hosted by:
http://blogs.vbcity.com      
  Home :: Syndication  :: Login

JulAugust 2004Sep
SMTWTFS
25262728293031
1234567
891011121314
15161718192021
22232425262728
2930311234

Articles

Archives

Topics

CONTACT

Fun but useful linkies

General

VS 2005

Wolfenstein ET

Tuesday, August 17, 2004 #

Ever wanted to display a status on a notifyicon in the system tray, but couldn't find a way to draw on top of an icon using the graphics object? Well, you can't.

Not to worry though. There's an easy way around: First create a new bitmap (or create one from an existing icon), create the graphics object and do the drawing, and finally recreate the icon by using the static FromHandle method of the Icon class on the GetHicon of the bitmap.

Here's a small example that, when run, displays a countdown in the system tray:

            [STAThread]

            static void Main()

            {

                  NotifyIcon ic = new NotifyIcon();

                  ic.Text="just a test ;-)";

                  ic.Visible=true;

 

                  for(int i=10;i>=0;i--)

                  {

                        ic.Icon=GetIcon(i);

                        System.Threading.Thread.Sleep(1000);

                  }

                  //The notifyicon is often not destroyed properly

                  //even with dispose. A good way to ensure it

                  //disappears from the taskbar is removing the Icon

                  ic.Icon=null;

            }

 

            private static Font iconfont = new Font(FontFamily.GenericSerif,20);

            private static Icon GetIcon(int nr)

            {

                  //Create a bitmap, the size of an icon

                  Bitmap bmp = new Bitmap(32,32);

                  //Create Graphics object for the bitmap (all drawing to the graphics object will be drawn on the bitmap)

                  Graphics g = Graphics.FromImage(bmp);

                  //Create a smokewhite background,draw the circle and the number

                  g.Clear(Color.WhiteSmoke);

                  g.DrawEllipse(Pens.Black,0,0,32,32);

                  SizeF s = g.MeasureString(nr.ToString(),iconfont);//to center the string

                  g.DrawString(nr.ToString(),iconfont,Brushes.Black,(32-s.Width)/2,(32-s.Height)/2);

                  //And finally, get the icon out the icon handle of the bitmap

                  return Icon.FromHandle(bmp.GetHicon());

            }

Of course drawing on top of an existing icon is also possible. Then, instead of creating a new bitmap, get the bitmap out of the icon by using the ToBitmap method of the original icon. eg:

Bitmap bmp = YourIconVariable.ToBitmap();

posted @ 11:48 AM