开发者

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

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 n开发者_运维百科ow, 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?


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.


Yes, you do not need to create a new ToolTip each time, a single ToolTipwill do. There is no issue if you do not know how many ToolTips you want, because if there is only one ToolTip say toolTip1, then you can use the following every time you want to change the ToolTip caption and control on some event. You only need one ToolTip instance per form.

toolTip1.SetToolTip(Current_pictureBox, "<tool tip string>");


  1. You only need one ToolTip instance per form.

  2. toolTip.SetToolTip(control, caption) - can use with many control, you can set caption for each control

  3. toolTip.ToolTipTitle - set tool tip title, the title is one for all control bonded with tool tip

for example :

public Form1()
{
    InitializeComponent();
    toolTip1.SetToolTip(button1, "btn1");
    toolTip1.SetToolTip(button2, "btn2");
    toolTip1.SetToolTip(button3, "btn3");
}


private void button4_Click(object sender, EventArgs e)
{
    toolTip1.ToolTipTitle = textBox1.Text;
}

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜