C# counter in a Tray Icon - utility
Below is a small class I wrote in order to put a small tray icon with a custom background color, foreground color, and a text.
The particularity of this application is that it does not use any form.
TrayCounter.cs
using System;
using System.Windows.Forms;
using System.Drawing;
namespace dms.windows
{
class TrayCounter
{
private string _text = "";
private string _tooltip = "";
private Brush _bg = Brushes.Green;
private Brush _fg = Brushes.Yellow;
public System.Windows.Forms.NotifyIcon notificationIcon = new NotifyIcon();
public TrayCounter()
{
Text = "";
}
public Brush Background
{
get
{
return _bg;
}
set
{
_bg = value;
Redraw();
}
}
public Brush Foreground
{
get
{
return _fg;
}
set
{
_fg = value;
Redraw();
}
}
public string Text
{
get
{
return _text;
}
set
{
_text = value;
Redraw();
}
}
public string Tooltip
{
get
{
return _tooltip;
}
set
{
_tooltip = value;
Redraw();
if (_tooltip.Length == 0)
_tooltip = "<empty>";
notificationIcon.Text = _tooltip;
notificationIcon.ShowBalloonTip(Int32.MaxValue, "Counter", _tooltip, ToolTipIcon.Info);
}
}
private void Redraw()
{
Bitmap bitmap = new Bitmap(16, 16);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.FillRectangle(_bg, new Rectangle(0, 0, 16, 16));
graphics.DrawString(_text, new Font("Arial Unicode MS", 5), _fg, new PointF(0, 0));
Icon icon = Icon.FromHandle(bitmap.GetHicon());
notificationIcon.Icon = icon;
notificationIcon.Visible = true;
notificationIcon.ContextMenu = new ContextMenu();
}
}
}