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方法。显示通知图标,我多次左/右点击它,事件就不会被激活。
答案 0 :(得分:2)
如果您只是定期检查,为什么不使用计时器而不是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");
}
}
}
答案 1 :(得分:0)
while(true)锁定主线程。
尝试用
替换while(true)块Application.Run();