R4cOOn
R4cOOn

Reputation: 2575

How to know when a UserControl is no longer used (no Close event)

I'm using UserControls inside a WinForm to display data. I'm also using the command pattern so that the UserControl registers a (weak) event and does stuff when the command is triggered.

On a WinForm I can unregister the events in the Close event. However there's no such event on a UserControl. I hooked up the events I thought would be fired when the UserControl is no longer in the display stack but could find nothing useful. To get by I check if the Parent is null and that worked for most of the cases.

Now I'd like to have a child UserControl of another UserControl (put the UserControl inside a TabControl) and the Parent property isn't going to be null for the child control anymore when the parent is no longer displayed.

Is there any way to know if the UserControl is used?

What I've tried so far: Dispose() doesn't get called straight away by the system so it's no useful; IsVisible doesn't get updated by the system either; there is no Close or Unload event fired.

Cheers.

Upvotes: 2

Views: 5754

Answers (3)

anonymous
anonymous

Reputation: 1

In the past I dealt with this problem by getting the parent form (using Control.ParentForm) and then hooking up to the FormClosing event directly.

The tricky part is knowing when to call ParentForm. It's not set when the user control is first created. Sometimes I override the OnLayout handler and monitor until the ParentForm is not null.

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 941455

It really is the Dispose() method. If it doesn't get called early enough then there's a bug in the code that uses the control. Using Controls.Clear() or Controls.Remove() for example.

The parent of a control always iterates its Controls collection and disposes the child controls when it gets disposed. Which makes disposing automatic, starting at the form's Dispose() which runs when the form is closed. It is however not automatic when you remove controls yourself.

Upvotes: 1

Steve Wong
Steve Wong

Reputation: 2256

There is a HandleDestroyed event on the Control that might work for you.

Upvotes: 3

Related Questions