Search code examples
c#notifyicon

Not updating systray notifyicon dynamically?


I have the following code that "should" draw a 2 onto the existing trayicon but when run the icon does not update? i have saved the bitmap to file and it does have the 2 draw on top as expected, do i need to refresh the tray icon somehow for it to update or am i going about this the wrong way

t_Elapsed:

Graphics canvas;
Bitmap iconBitmap = new Bitmap(16, 16);
canvas = Graphics.FromImage(iconBitmap);

canvas.DrawIcon(Properties.Resources.SystemTrayApp, 0, 0);

StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;

canvas.DrawString(
    "2",
    new Font("Calibri", 8, FontStyle.Bold),
    new SolidBrush(Color.FromArgb(40, 40, 40)),
    new RectangleF(0, 3, 16, 13),
    format
);

NotifyIcon ni;
ni = new NotifyIcon();
ni.Icon = Icon.FromHandle(iconBitmap.GetHicon());
ni.Visible = true;

t.Start();

heres the code where notifyicon is initially generated...

namespace SystemTrayApp
{
class ProcessIcon : IDisposable
{
    NotifyIcon ni;

    public ProcessIcon()
    {
        ni = new NotifyIcon();
    }

    public void Display()
    {   
        ni.MouseClick += new MouseEventHandler(ni_MouseClick);
        ni.Icon = Resources.SystemTrayApp;
        ni.Text = "Auto Sort";
        ni.Visible = true;

        ni.ContextMenuStrip = new ContextMenus().Create();
    }

    public void Dispose()
    {
        ni.Dispose();
    }
}
}

here is the main part where it seems the initial ProcessIcon is called.

static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        // Show the system tray icon.                   
        using (ProcessIcon pi = new ProcessIcon())
        {
            pi.Display();

            t = new System.Timers.Timer();
            t.AutoReset = false;
            t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
            t.Interval = 2000;
            t.Start();

            // Make sure the application runs!
            Application.Run();               
        }
    }

this main part starts the timer loop that you can see in the first part, where i am trying to update the tray icon and failing ( well it is creating a new icon in addition to the existing one as suggested )

how can the timer loop access the pi object to update the icon ?

Thanks


Solution

  • Found the answer, i need to move the timer functions into the same class that created the tray icon, then from there i start the timer and am able to update the icon as expected. Also added the dispose as suggested :)

    Thanks