views:

29

answers:

1

I have a simple Windows Form that hosts property controls at runtime. When the user clicks Close [X] I want to keep the window and its contents alive rather than killing it by handling the FormClosing event, canceling the event and simply hiding the form.

That's fine but at close of the application I need to actually close the window. I implemented the below but it feels kludgey. Is there a simpler, more clever way to handle this situation? (The form's controller calls KillForm explicitly after it receives a closing event from the main window.)

Friend Class HostForm
    Private _hideInsteadOfClosing As Boolean = True

    Private Sub HostForm_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) _
    Handles Me.FormClosing
        If _hideInsteadOfClosing Then
            Me.Hide()
            e.Cancel = True
        End If
    End Sub

    Public Sub KillForm()
        _hideInsteadOfClosing = False
        Me.Close()
    End Sub
End Class
+2  A: 

You can examine the value of the CloseReason property of the event args object. If it is UserClosing, hide the form, otherwise close it. For all possible values of this property, check the CloseReason enumeration documentation.

Fredrik Mörk