NotifyIcon不会被丢弃

问题描述 投票:0回答:1

在我的家庭作业申请中;我需要创建一个应用程序,其中还需要使用NotifyIcon。我遇到了一个问题,我无法理解为什么代码从未达到Dispose事件。我实现IDisposable(以便能够处理NotifyIcon);在dispose事件中添加断点之后;我可以看到代码永远不会到达Disposed Event。我真的不明白为什么它没有到达那里。不管我在哪里称呼“处置”,它都无法实现。因此(我相信),还会出现其他问题;像托盘图标不会消失。

我目前正在关注该主题:NotifyIcon remains in Tray even after application closing but disappears on Mouse Hover

谁能帮助我了解发生这种情况的原因/我想念什么?

我的班级代码:

    private NotifyIcon trayIcon;

    public void CreateTrayIcon()
    {
        if (trayIcon == null) { trayIcon = new NotifyIcon(); }
        trayIcon.Text = "My Tray Application";
        trayIcon.Icon = Properties.Resources.AppIcon;
        trayIcon.Disposed += TrayIcon_Disposed;

        trayIcon.Visible = true;
    }

    private void TrayIcon_Disposed(object sender, EventArgs e) // Unreacheable Code
    {
        if (ctMenu != null) { ctMenu.Dispose(); ctMenu = null; }
        if (trayIcon != null) { trayIcon.Icon.Dispose(); trayIcon = null; }
    }

    protected virtual void Dispose(bool Disposing)
    {
        if (Disposing)
        {
           trayIcon.Dispose();
        }
    }
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

并致电NotifyIcon处置主表格; Form_ClosingEvent

private void Form_closing(object sender, FormClosingEventArgs e)
{
    trayIcon.Dispose();
}
c# dispose idisposable notifyicon
1个回答
0
投票

好的;我发现了问题...

我的问题背后的原因;是在我假设已订阅FormClosing事件的情况下(老实说:我确定已经订阅了该事件。我必须进行某种回滚并错误地删除了它)。

解决方案:只需要进行检查并确保已订阅该事件。

© www.soinside.com 2019 - 2024. All rights reserved.