title: Toggle form visibility on NotifyIcon click and hide it on click elsewhere
body: <p>I have an application which is in system tray. I want to make it visible when the user clicks on the <code>notifyIcon</code>, 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). </p>
  
  <p>My code looks like this:</p>
  
  <pre><code>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);
          }
      }
  }
  </code></pre>
  
  <p>The problem with the code is that <code>onDeactivated</code> gets called before the click call, which hides the form and <code>notifyIcon1_MouseClicked</code> than just re-shows it. If I could detect if the focus was lost due to a click on <code>notifyIcon</code> or elsewhere it would solve the problem.</p>
  
  <p>I've done my research and found a similar thread, but the solution just detected if the mouse position is over the tray when <code>onDeactivated</code> gets called: <a href="https://stackoverflow.com/questions/6926281/c-toggle-window-by-clicking-notifyicon-taskbar-icon">C# toggle window by clicking NotifyIcon (taskbar icon)</a> </p>
  
  <p>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 <code>onDeactivated</code> event won't get fired.
  I want to get the same functionality as the system volume app.</p>