Search code examples
vb.netwinformsvisual-studio-2005modeless

Where do I control the behavior of the "X" close button in the upper right of a winform?


I'm venturing into making my VB.NET application a little better to use by making some of the forms modeless.

I think I've figured out how to use dlg.Show() and dlg.Hide() instead of calling dlg.ShowDialog(). I have an instance of my modeless dialog in my main application form:

Public theModelessDialog As New dlgModeless

To fire up the modeless dialog I call

theModelessDialog.Show()

and within the OK and Cancel button handlers in dlgModeless I have

Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
    Me.DialogResult = System.Windows.Forms.DialogResult.OK
    Me.Hide()
End Sub

Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
    Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
    Me.Hide()
End Sub

and that seems to work fine.

The "X" button in the upper right is getting me, though. When I close the form with that button, then try to reopen the form, I get

ObjectDisposedException was unhandled. Cannot access a disposed object.

I feel like I'm most of the way there but I can't figure out how to do either of the following:

  • Hide that "X" button
  • Catch the event so I don't dispose of the object (just treat it like I hit Cancel)

Any ideas?

The class of this dialog is System.Windows.Forms.Form.


Solution

  • Use Me.Close() to hide the form. To open it, use the following snippet:

    If theModelessDialog.IsDisposed Then
        theModelessDialog = New dlgModeless
    End If
    dlgModeless.Show()
    

    If this is saving data, then you'll need to figure some way of storing it (perhaps in a static variable/s in the form). This is the proper way to do what you are trying to achieve though.

    You'll also have to forgive me if my VB is off, it's been a while.