Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What event signals that a UserControl is being destroyed?

I have a UserControl-derived control the displays some information fetched from a web server. I'm currently in the process of making the initialization of the control asyncronous, to improve responsiveness.

In my Load event handler, I'm creating a CancellationTokenSource, and using the associated Token in the various async calls.

I now want to ensure that if the user closes the form before the async operation completes, the operation will be cancelled. In other words, I want to call Cancel on the token.

I'm trying to figure out where to do this. If there was an Unload event that I could trap, then that would be perfect - but there isn't. In fact, I can't find any event that looks suitable.

I could trap the close event for the containing Form, but I really wanted to keep everything local to my UserControl.

Suggestions?

like image 761
Gary McGill Avatar asked Sep 18 '12 09:09

Gary McGill


2 Answers

I suggest the Control::HandleDestroyed event. It is raised, when the underlying HWnd is destroyed (which usually happens, when the parent form is closed). To handle it in your own UserControl, you should override OnHandleDestroyed.

You have full access to the Control's properties at this moment, because it is not yet disposed of.

like image 103
Stephan Avatar answered Nov 08 '22 14:11

Stephan


Another solution

    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
    }
like image 13
Avram Avatar answered Nov 08 '22 14:11

Avram