c# - NotifyIcon 单击事件未触发

标签 c# windows console-application

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();
    }
}

以上是一个最小的例子。由于某种原因,从未调用 NotifyIconInteracted 方法。通知图标出现,我多次左键/右键单击它,但事件不会触发。

最佳答案

如果您只是进行定期检查,为什么不使用计时器而不是 while 循环呢?使用计时器不会像 while() 循环那样锁定程序。

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");
        }
    }
}

关于c# - NotifyIcon 单击事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39130681/

相关文章:

c# - 我在哪里可以存储从站点下载的可执行代码并运行它?

c# - 属性声明上方的方括号语法

windows - 在特定文件夹中启动 cmder ConEmu 控制台

C#包结构系统

c# - 如何在 UI 中对计数器值进行动画处理以增加 C# WPF 中的值?

c# - StringWriter.ToString() 处的 OutOfMemoryException

c++ - 在 Windows 8 下使用 Tbb 构建错误 Qt creator

windows - Powershell 脚本 : SSH into Server

c# - 如何在控制台应用程序中隐藏输出(不是窗口)?

python - 尝试使用 urwid 创建控制台屏幕时出现“断言错误”