I have an application which is in system tray. I want to make it visible when the user clicks on the notifyIcon
, if it's not visible already. If it is already visible it should be hidden. Also when the user clicks anywhere else except on the form the form should hide (if it's visible).
My code looks like this:
protected override void OnDeactivated(EventArgs e)
{
showForm(false);
}
public void showForm(bool show)
{
if(show)
{
Show();
Activate();
WindowState = FormWindowState.Normal;
}
else
{
Hide();
WindowState = FormWindowState.Minimized;
}
}
private void notifyIcon1_MouseClicked(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (WindowState != FormWindowState.Normal)
{
showForm(true);
}
}
}
The problem with the code is that onDeactivated
gets called before the click call, which hides the form and notifyIcon1_MouseClicked
than just re-shows it. If I could detect if the focus was lost due to a click on notifyIcon
or elsewhere it would solve the problem.
I've done my research and found a similar thread, but the solution just detected if the mouse position is over the tray when onDeactivated
gets called: C# toggle window by clicking NotifyIcon (taskbar icon)
UPDATE:
The solution I posted only detects if the user's mouse is over the tray icons in the taskbar, so if you click on any other tray the onDeactivated
event won't get fired.
I want to get the same functionality as the system volume app.