I am working on a .NET WPF project using Visual Studio 2022 and I added tray icon functionality to my app. I also show toast notification whenever my app is minimized to windows tray. Everything works fine except when I click outside border of toast notification, it does not disappear. I think it is a focus issue but can not able to overcome that. Any idea how to solve this?
My code:
public NotifyIcon m_notifyIcon;
public MainWindow()
{
InitializeComponent();
m_notifyIcon = new NotifyIcon();
m_notifyIcon.BalloonTipText = "The app has been minimised. Click the tray icon to show.";
m_notifyIcon.BalloonTipTitle = "The App";
m_notifyIcon.Text = "The App";
m_notifyIcon.DoubleClick += new EventHandler(m_notifyIcon_Click);
m_notifyIcon.MouseDown += new MouseEventHandler(Notifier_MouseDown);
Hide();
if (m_notifyIcon != null)
m_notifyIcon.ShowBalloonTip(2000);
CheckTrayIcon();
}
}
private WindowState m_storedWindowState = WindowState.Normal;
void OnStateChanged(object sender, EventArgs args)
{
if (WindowState == WindowState.Minimized)
{
Hide();
if (m_notifyIcon != null)
m_notifyIcon.ShowBalloonTip(2000);
}
else
m_storedWindowState = WindowState;
}
void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs args)
{
CheckTrayIcon();
}
void m_notifyIcon_Click(object sender, EventArgs e)
{
Show();
WindowState = m_storedWindowState;
}
void CheckTrayIcon()
{
ShowTrayIcon(true);
}
void ShowTrayIcon(bool show)
{
if (m_notifyIcon != null)
m_notifyIcon.Visible = show;
}
void Notifier_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ContextMenu menu = (ContextMenu)this.FindResource("NotifierContextMenu");
menu.IsOpen = true;
IntPtr handle = ((HwndSource)PresentationSource.FromVisual(menu)).Handle;
ApiHelper.SetForegroundWindow(handle);
}
}