December 14, 2008

Adding App Icon To Taskbar

Adding you WinForm app to the taskbar Some missing points 1. As it is, when minimized, the window will appear both in the taskbar (minimised) in the system tray. To fix this set the main form property 'ShowInTaskbar' to false;
public XXXForm()
{
 InitializeComponent();
 this.ShowInTaskbar = false;
}
Change the 'notifyIcon_DoubleClick':
private void notifyIcon_DoubleClick(object sender, EventArgs e)
{
 Show();
 ShowInTaskbar = true;
 WindowState = FormWindowState.Normal;
}
Also I prefer to override the resize rather than pick up an event
protected override void OnResize(EventArgs e)
{
 base.OnResize(e);
 // Hide the form when it is minimised
 if (FormWindowState.Minimized == WindowState)
  Hide();
}
I also added a menu timer to ensure that when the mouse leaves the context menu the menu dissappears after a short time (3 seconds). Aagh, next bit is for WPF based taskbar app.
using System.Windows.Threading;
...
public partial class AppMainWindow : Window
{
...
  private DispatcherTimer timer = null;
...
    public AppMainWindow ()
    {
      InitializeComponent();
...
      contextMenu = (ContextMenu)this.FindResource("NotifierContextMenu");
      contextMenu.Closed += new RoutedEventHandler(menu_Closed);
      contextMenu.Opened += new RoutedEventHandler(menu_Opened);
      CreateMenuTimer();
    }
...
  #region Timer

  private void CreateMenuTimer()
  {
    const int MILLISECOND = 10000;
    timer = new DispatcherTimer();
    // Disable (stop) it 
    timer.IsEnabled = false;
    // Set timer event interval
    timer.Interval = new TimeSpan((long)(3000 * MILLISECOND));
    // Timer events
    timer.Tick += new EventHandler(timer_Tick);
  }

  void timer_Tick(object sender, EventArgs e)
  {
    if (contextMenu.IsOpen)
    {
      if (contextMenu.IsMouseOver && contextMenu.IsMouseDirectlyOver)
      {
        contextMenu.IsOpen = false;
      }
    }
    else
    {
      timer.Stop(); 
    }
  }

  void menu_Opened(object sender, RoutedEventArgs e)
  {
    timer.Start();
  }

  void menu_Closed(object sender, RoutedEventArgs e)
  {
    timer.Stop(); 
  }

  #endregion Timer



No comments: