Working Experience - How to handle the destroyed event of UserControl

正文

问题: UserControl 如何在父窗体(程序)关闭时, 释放一些需要手动释放的资源
方法: 使用 Control.FindForm() 获取父窗体, 从而得到父窗体的 Closing/Closed 事件

Form parentForm;

// 可以使用其他方式触发
protected override void OnParentChanged(EventArgs e)
{
    base.OnParentChanged(e);

    if (parentForm != null)
    {
        parentForm.Closing -= parentForm_Closing;
    }
    parentForm = FindForm();

    if (parentForm != null)
        parentForm.Closing += parentForm_Closing;
}

void parentForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    parentForm.Closing -= parentForm_Closing;
    parentForm = null;
    //closing code
}

参考

stack overflow - What event signals that a UserControl is being destroyed?

posted @ 2019-05-17 10:25  郑大峰  阅读(118)  评论(0编辑  收藏  举报