该应用程序从一个空的 C# 项目启动,输出类型设置为“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()
}
}
我WinForms
用作基础,因为WPF
没有系统托盘图标控件。但是,所有其他窗口都是WPF
. 我像这样运行它们:
static void ShowUI()
{
MainUI wnd = new MainUI(); //MainUI is a System.Windows.Window (WPF)
wnd.Show();
}
我有一个参考WindowsFormsIntegration
。窗口显示WPF
正确,一切似乎都正常。但:
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;
}
...抛出一个System.ObjectDisposedException
. 扩展方法ToImageSource()
在纯WPF
项目时运行良好,但自从我切换到WinForms
上下文后,它就停止工作并抛出异常。
我尝试通过将单线分成几个步骤进行调试:
System.Drawing.Icon icon = Properties.Resources.myIcon; //works
ImageSource imgsrc = icon.ToImageSource(); //works
wnd.Icon = imgsrc; //System.ObjectDisposedException
不知道发生了什么。这是不运行实际的副作用WPF
Application.Run()
吗?