I would like to have a system tray icon appear only when I need to show a balloon tip, then hide the icon when the balloon tip is closed.
However, once the icon is shown, I can't get it to disappear because the event handler is not fired:
public partial class MainWindow : Window {
public static NotifyIcon trayIcon = new NotifyIcon();
public MainWindow() {
InitializeTrayIcon();
}
void InitializeTrayIcon() {
trayIcon.Text = "My App";
trayIcon.Icon = MyApp.Properties.Resources.myIcon;
trayIcon.Visible = false;
//the following never gets fired:
trayIcon.BalloonTipClosed += (sender, e) => {
trayIcon.Visible = false;
};
}
public static void ShowTrayNotification(ToolTipIcon icon, string title, string text, int duration) {
trayIcon.Visible = true;
trayIcon.ShowBalloonTip(duration, title, text, icon);
}
}
The ShowTrayNotification()
is called from a method that is triggered by a timer:
public abstract class Watcher {
protected System.Timers.Timer myTimer = new System.Timers.Timer(1000);
//the following is called in a subclass of Watcher, which is instantiated in MainWindow
protected void SetupMyTimer() {
myTimer.AutoReset = true;
myTimer.Elapsed += myTimer_Elapsed;
myTimer.Start();
}
protected virtual void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
myTimer.Enabled = false;
MyTimerElapsedCallback();
myTimer.Enabled = true;
}
void MyTimerElapsedCallback() {
MainWindow.ShowTrayNotification(ToolTipIcon.Info, "Hello There!", "Balloon text here.", 5000);
}
}
So the balloon is shown. But BalloonTipClosed
in MainWindow
is never fired.
I have tried:
putting the (1) creation of the
NotifyIcon
, (2) displaying of balloon, and (3) settingBalloonTipClosed
all inMainWindow
, and it works fine (i.e.BalloonTipClosed
is fired)putting (1), (2), and (3) in
SetupMyTimer()
and it works fine as wellputting (1), (2), and (3) in
MyTimerElapsedCallback()
and it does not work (i.e.BalloonTipClosed
is not fired)changing
BalloonTipClosed
toBalloonTipClicked
and it does not work as well.using non-lambda BalloonTipClosed EventHandler, does not work.
with this, I am thinking the problem has to do with the Timer, but I don't know how it's affecting the event handler, nor how to fix.
Any ideas?