gpt4 book ai didi

c# - 如何在 UserControl 中自动清理 ToolTip

转载 作者:太空狗 更新时间:2023-10-29 23:25:44 26 4
gpt4 key购买 nike

我一直在追踪内存泄漏,并将其缩小到在 UserControl 派生类中分配的工具提示。

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 的引用仍然存在。

我添加了这样的关机方法:

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

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

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

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

最佳答案

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

只是调用:

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

关于c# - 如何在 UserControl 中自动清理 ToolTip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8228693/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com