The application was started from an empty C# project, output type set to "Windows App":
using System.Windows.Forms;
static class Program
{
static System.Windows.Forms.NotifyIcon notifyIcon;
static System.Drawing.Icon LockedIcon = Properties.Resources.icon_locked;
[STAThread]
Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
notifyIcon = new NotifyIcon()
{
Icon = LockedIcon,
ContextMenu = ContextualMenu(),
Visible = true
};
Application.Run()
}
}
I am using WinForms
as a base since WPF
doesn't have a systray icon control. However, all the other windows are WPF
. I am running them like this:
static void ShowUI()
{
MainUI wnd = new MainUI(); //MainUI is a System.Windows.Window (WPF)
wnd.Show();
}
I have a reference to WindowsFormsIntegration
. The WPF
window shows correctly and everything seems to work. But:
public MainUI()
{
this.Loaded += (o,e) => this.Icon = Properties.Resources.myIcon.ToImageSource();
InitializeComponent();
}
public static System.Windows.Media.ImageSource ToImageSource(this System.Drawing.Icon i)
{
System.Windows.Media.ImageSource imgsrc;
using (System.IO.MemoryStream iconStream = new System.IO.MemoryStream())
{
i.Save(iconStream);
iconStream.Seek(0, System.IO.SeekOrigin.Begin);
imgsrc = System.Windows.Media.Imaging.BitmapFrame.Create(iconStream);
}
return imgsrc;
}
...throws a System.ObjectDisposedException
. The extension method ToImageSource()
worked fine when it was a pure WPF
project, but ever since I switched to a WinForms
context, it stopped working and throws that exception.
I tried debugging by splitting the one-liner into several steps:
System.Drawing.Icon icon = Properties.Resources.myIcon; //works
ImageSource imgsrc = icon.ToImageSource(); //works
wnd.Icon = imgsrc; //System.ObjectDisposedException
Not sure what's happening. Is it a side effect of not running the actual WPF
Application.Run()
?