Avalanchis
Avalanchis

Reputation: 4559

How to automate clean up of ToolTip in UserControl

I've been tracking down a memory leak and I've narrowed it down to a ToolTip that is allocated in a UserControl-derived class.

The ToolTip is allocated in the allocated in the control's constructor and initialized in the Load event like this:

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");
    }    
}

The control's parent has a lifetime that exceeds the control's lifetime. This control is created on the fly and added to a panel control and then subsequently removed from the panel control.

I found that the control's Dispose member was not getting called, apparently because references to the ToolTip remain.

I added a Shutdown method like this:

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

Calling the Shutdown method eliminates the leak and Dispose is eventually called.

Unfortunately, this solution requires that whoever uses the control remembers to call the Shutdown method when they are finished with it.

I'd like to know if there is some way that I can automate this so that it happens without the need to call the Shutdown method explicitly.

Upvotes: 5

Views: 5580

Answers (2)

PRR
PRR

Reputation: 1178

Also in your control dispose method you need to explicitly call dispose on your tooltip.

Upvotes: 2

LarsTech
LarsTech

Reputation: 81610

You aren't showing the code for how you are disposing your UserControl from your Panel.

Just calling:

panel1.Controls.Remove(userControl1);

isn't going to dispose the UserControl.

You need to specifically call:

userControl1.Dispose();

which will also automatically remove it from the Panel. In your UserControl, if you need to do your own clean up, try subscribing to it's own Dispose event:

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();
}

Upvotes: 4

Related Questions