为什么我不能让在另一个类中实现的 NotifyIcon 在退出时消失?
以下是来自新制作的 Windows 窗体项目的一些代码,没有任何其他更改:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Bitmap blah = new Bitmap(16, 16);
using (Graphics blah2 = Graphics.FromImage(blah))
{
blah2.FillRectangle(new SolidBrush(Color.Black), new Rectangle(0, 0, 16, 16));
}
NotifyIcon2 n = new NotifyIcon2();
n.NotifyIcon = new NotifyIcon();
n.NotifyIcon.Icon = Icon.FromHandle(blah.GetHicon());
n.NotifyIcon.Visible = true;
}
class NotifyIcon2 : IDisposable
{
public NotifyIcon NotifyIcon { get; set; }
private bool disposed;
~NotifyIcon2()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this); // The finalise process no longer needs to be run for this
}
protected virtual void Dispose(bool disposeManagedResources)
{
if (!disposed)
{
try
{
NotifyIcon.Dispose();
}
catch { }
disposed = true;
}
}
}
}
从我所看到的,在 protected virtual void Dispose
中,NotifyIcon
在它被释放时已经被释放了。被执行(解释了为什么我在那里放置了一个 try/catch 块),所以我无法对其图标执行任何操作。
那么我该如何让它消失呢?
Here's some code from a freshly made Windows Forms project, with nothing else changed:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Bitmap blah = new Bitmap(16, 16);
using (Graphics blah2 = Graphics.FromImage(blah))
{
blah2.FillRectangle(new SolidBrush(Color.Black), new Rectangle(0, 0, 16, 16));
}
NotifyIcon2 n = new NotifyIcon2();
n.NotifyIcon = new NotifyIcon();
n.NotifyIcon.Icon = Icon.FromHandle(blah.GetHicon());
n.NotifyIcon.Visible = true;
}
class NotifyIcon2 : IDisposable
{
public NotifyIcon NotifyIcon { get; set; }
private bool disposed;
~NotifyIcon2()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this); // The finalise process no longer needs to be run for this
}
protected virtual void Dispose(bool disposeManagedResources)
{
if (!disposed)
{
try
{
NotifyIcon.Dispose();
}
catch { }
disposed = true;
}
}
}
}
From what I can see, in protected virtual void Dispose
, the NotifyIcon
has already been disposed when it gets executed (explaining why I put a try/catch block there), so I can't do anything about its icon.
So how do I make it disappear?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实证明,处理父类会同时删除子类。
FormClosing += (sender, e) => n.Dispose();
(请参阅 BoltClock 对问题的评论中提供的链接)
Turns out disposing of the parent class will take out the child along with it.
FormClosing += (sender, e) => n.Dispose();
(see the link provided in BoltClock's comment on the question)