首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NotifyIcon单击事件未触发

NotifyIcon单击事件未触发
EN

Stack Overflow用户
提问于 2016-08-24 18:34:45
回答 2查看 2.8K关注 0票数 1
代码语言:javascript
复制
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方法从未被调用过。“通知”图标出现,我多次左/右击它,事件就不会触发。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-08-24 19:38:14

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

代码语言:javascript
复制
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");
        }
    }
}
票数 3
EN

Stack Overflow用户

发布于 2016-08-24 19:13:21

当(True)锁定主线程时。

尝试将while(true)块替换为

代码语言:javascript
复制
Application.Run();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39130681

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档