Steve
Steve

Reputation: 11963

NotifyIcon click event not firing

class MainProgram
{
    static NotifyIcon _notifyIcon;

    public static void Main()
    {
        _notifyIcon = new NotifyIcon();
        _notifyIcon.Icon = new Icon("icon.ico");
        _notifyIcon.Click += NotifyIconInteracted;
        _notifyIcon.Visible = true;

        while(true)
        {
            Thread.Sleep(1000);
        }
    }

    static void NotifyIconInteracted(object sender, EventArgs e)
    {
        throw new NotImplementedException();
    }
}

Above is a minimum example. For some reason the NotifyIconInteracted method is never called. The notify icon shows up, I left/right click on it multiple times and the event just won't fire.

Upvotes: 2

Views: 3492

Answers (2)

briandoesdev
briandoesdev

Reputation: 141

Why not use a timer instead of a while loop if you're only doing a periodic check? Using a timer will not lock up the program like a while() loop.

using System;
using System.Timers;
using System.Windows.Forms;

namespace SONotify
{
    class Program
    {
        private static System.Timers.Timer _timer;
        private static NotifyIcon _notify;

        static void Main(string[] args)
        {
            Console.WriteLine("Press enter to exit");
            SetIcon();
            SetTimer();

            Application.Run();

            Console.ReadLine();

            _timer.Stop();
            _timer.Dispose();
        }

        private static void SetIcon()
        {
            _notify = new NotifyIcon();
            _notify.Icon = new System.Drawing.Icon("icon.ico");
            _notify.Click += NotifyIconInteracted;
            _notify.Visible = true;
        }

        private static void SetTimer()
        {
            _timer = new System.Timers.Timer(2000); //Timer goes off every 2 seconds
            _timer.Elapsed += Timer_Elapsed;
            _timer.AutoReset = true;
            _timer.Enabled = true;
        }

        private static void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("Timer fired");
        }

        private static void NotifyIconInteracted(object sender, EventArgs e)
        {
            Console.WriteLine("Icon clicked");
        }
    }
}

Upvotes: 3

Massuda
Massuda

Reputation: 31

That while(true) locks the main thread.

Try to replace the while(true) block with

Application.Run();

Upvotes: 0

Related Questions