System.Drawing.Icon and embedded rersources

To use an icon resource embedded into your assemply: 

1) Add icon to project and make it an “Embedded Resource” type (no need to copy to output directory).

2) Construct your System.Drawing.Icon like this:


new Icon(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("MyShinyApp.hammer.ico"));

Where MyShinyApp is the value specified in “Default namespace” property of your project (Application tab of project properties) and hammer.ico is the name of your icon.

Minimize to tray icon in WPF

I had to do a bit of searching so, here’s how to minimize your WPF app to a tray icon.  Assume your window is called Window1 for the code below.  Trap Closing, StateChanged and IsVisibleChanged (see xaml). 

xaml:

<window x:Class="MyApp.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="WCFAppVisualHost" Height="383" Width="680" Closing="OnClose" StateChanged="OnStateChanged" IsVisibleChanged="OnIsVisibleChanged"
  >

Associated cs:

private System.Windows.Forms.NotifyIcon m_notifyIcon;

public Window1()
{
    // initialise code here
    m_notifyIcon = new System.Windows.Forms.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.Icon = new System.Drawing.Icon("TheAppIcon.ico");
    m_notifyIcon.Click += new EventHandler(m_notifyIcon_Click);
}

void OnClose(object sender, CancelEventArgs args)
{
    m_notifyIcon.Dispose();
    m_notifyIcon = null;
}

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(!IsVisible);
}

void ShowTrayIcon(bool show)
{
    if (m_notifyIcon != null)
        m_notifyIcon.Visible = show;
}