How to detect closed form?

  • Thread starter Thread starter Skrenek
  • Start date Start date
S

Skrenek

I have opened form from another form and I have an variable with reference
on it. But what if someone close referenced form? I tryed to test an
variable on Nothing value but there is still reference on closed form. The
questin is: How can I find out that the referenced form is closed.

I have two ideas:
1) Exception handling
2) Handle closed event of closed form

Is there some better way?

And another problem. When a referenced form is closed, I can still run
frm.Hide() without throwing exception, but frm.Show() fires exception.
Object is closed, so why frm.Hide() doesn't throw the exception too?

Thanks Martin Skrenek
 
Hi Skrenek,

The normal way to detect a form closing is to handle the Form.Closing event.
You should only use exception handling for true "exceptions" -- things that
you don't expect to happen normally.

If you want to prevent the user from closing the form, you can set the
CancelEventArgs.Cancel property to true. For example, if you wanted to hide
the form instead of closing it, you could could cancel the Closing event and
call Me.Hide() in the Closing event handler.

There are samples in the documentation:
ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.1033/cpref/html/frlrfSystemWindows
FormsFormClassClosingTopic.htm

You can't show a form after it's been closed because the Close event also
disposes the controls on the form (gets them ready for garbage collection),
and they can't be brought back to life after that. Once a form's been
closed, it's gone -- you'll have to create a new instance of the form to
show it again. The CLR probably lets you call Hide just because it's
redundant -- a form that's been closed is already non-visible.

Hope this helps,
Robert Jacobson
 
An approach I have used in order for forms to
communicate. In the calling form declare a property to be
written by the called form. When an instance of the
called form is created with new() pass the calling form.
It may be passed as a specific form or an object. If the
called form can be shown from different objects (classes)
use the general object type. When the called form closes,
write the property in the called from from the 'closing'
event. The calling form test the written proptery to
determine if the form already exists in which case
calledformed.activate will redisplay the form an give it
focus. If the property has been cleared by the called
form, it must be reinitiated by new and show or showdialog.
 
Back
Top