开发者

Why can't I make my NotifyIcon implemented in another class disappear upon exit?

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 Notify开发者_高级运维Icon 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?


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜