I just want to replace the task bar button of my winforms application by a tray notification icon. That means, if the user left-clicks the icon, the form should be activated if it wasn't focused, otherwise minimized or hidden.
I read lots and lots of articles about properly using a NotifyIcon
, and it seems I have to accept a hackish solution. So, what's the most proper way?
I got it mostly to run, but now I'm stuck at detecting if my form was active already - because when clicking the icon, the form looses focus, so I cannot check the Focused
property.
The following code does not yet solve this, so if the form was just hidden by other windows, you have to click 2 times, because the first click minimizes.
How can it be improved?
private void FormMain_Resize(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized)
Hide();
}
private void notifyIcon_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
if (WindowState == FormWindowState.Minimized) {
WindowState = FormWindowState.Normal;
Show();
Activate();
}
else {
Hide();
WindowState = FormWindowState.Minimized;
}
}
(I also don't understand why the Click
event fires on right-clicking, which already opens the context menu in my case...)
(And of course it would be nice to have a proper minimize animation, but there are other questions here, where this wasn't really solved)
(I know I said Focused
, but if the form was already fully visible (but maybe not focused), and the user clicks the tray icon, he most likely wants to hide it)