How can I change the text of an existing ToolTip control, in a PictureBox in my WinForm application?

Pure.Krome picture Pure.Krome · Aug 30, 2011 · Viewed 26.5k times · Source

I have a winform application which has a dynamic number (based on a database value) of PictureBoxes. Each P-Box has a Tooltip control.

How can I change the ToolTip Text without having any memory leaks? Right now, I've got the following code, but it's leaking memory => the previous ToolTip controls are not getting GC'd.

BTW, this is a background thread that is trying to update the main UI thread....

if (pictureBox == null || !pictureBox.IsHandleCreated) {
    continue;
}

Action setTooltipAndImage = () => {
    var toolTip = new ToolTip();
    GameServer tempGameFile = gameServer;
    toolTip.SetToolTip(pictureBox, string.Format(...));
    pictureBox.Image = Resources.RedButton;
};

if (pictureBox.InvokeRequired) {                        
    pictureBox.Invoke(setTooltipAndImage);
} else {
    setTooltipAndImage();
}

As I said - this works but it's leaking.

Anyone have any suggestions?

Answer

Hand-E-Food picture Hand-E-Food · Aug 30, 2011

Don't create a new ToolTip each time. Add a ToolTip to the form using the visual designer, like you would for any other control or component. Call toolTip.SetToolTip(...) on the form's tool tip each time. The ToolTip will be disposed when the Form is disposed.