簡體   English   中英

為什么我不能使在另一個類中實現的NotifyIcon在退出時消失?

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

這是新制作的Windows Forms項目中的一些代碼,沒有其他更改:

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 DisposeNotifyIcon在執行時已經被丟棄(解釋為什么我在其中放置try / catch塊),因此我對其圖標無能為力。

那么如何使它消失呢?

事實證明,處置父班將帶走孩子。

FormClosing += (sender, e) => n.Dispose();

(請參閱BoltClock對問題的評論中提供的鏈接)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM