如何在UserControl中自动清理ToolTip

时间:2011-11-22 14:47:09

标签: c# .net winforms .net-4.0 user-controls

我一直在追踪内存泄漏,我将其缩小为在UserControl派生类中分配的ToolTip。

ToolTip在控件的构造函数中分配,并在Load事件中初始化,如下所示:

public class CommonProfile : System.Windows.Forms.UserControl
{
    private ToolTip toolTip1;

    ...

    public CommonProfile()
    {
        InitializeComponent();

        // Create the ToolTip and associate with the Form container.
        toolTip1 = new ToolTip(this.components);
    }

    private void CommonProfile_Load(object sender, System.EventArgs e)
    {
        // Set up the delays for the ToolTip.
        toolTip1.AutoPopDelay = 5000;
        toolTip1.InitialDelay = 1000;
        toolTip1.ReshowDelay = 500;
        // Force the ToolTip text to be displayed whether or not the form is active.
        toolTip1.ShowAlways = true;

        // Set up the ToolTip text
        toolTip1.SetToolTip(this.btnDeleteEntry, "Delete this Profile");
        toolTip1.SetToolTip(this.lblProfileType, "Edit this Profile");
        toolTip1.SetToolTip(this.lblProfileData, "Edit this Profile");
        toolTip1.SetToolTip(this.picFlagForUpdate, "Toggle Flag for Update");
    }    
}

控件的父级的生命周期超过了控件的生命周期。此控件即时创建并添加到面板控件中,然后从面板控件中删除。

我发现控件的Dispose成员没有被调用,显然是因为对ToolTip的引用仍然存在。

我添加了一个这样的Shutdown方法:

public void Shutdown()
{
    toolTip1.RemoveAll();
}

调用Shutdown方法可以消除泄漏,并最终调用Dispose。

不幸的是,这个解决方案要求使用控件的人记住在完成后调用Shutdown方法。

我想知道是否有某种方法可以自动执行此操作,而无需显式调用Shutdown方法。

2 个答案:

答案 0 :(得分:3)

您没有显示有关如何从UserControl处理Panel的代码。

只需致电:

panel1.Controls.Remove(userControl1);

不会处置UserControl

您需要专门致电:

userControl1.Dispose();

也会自动将其从Panel中删除。在UserControl中,如果您需要自己清理,请尝试订阅它自己的Dispose事件:

private ToolTip toolTip1;

public UserControl1() {
  InitializeComponent();
  // tooltip initialization
  this.Disposed += UserControl1_Disposed;
}

private void UserControl1_Disposed(object sender, EventArgs e) {
  if (toolTip1 != null)
    toolTip1.Dispose();
}

答案 1 :(得分:1)

同样在您的控制配置方法中,您需要在工具提示上明确调用dispose。