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

John picture John · May 15, 2010 · Viewed 65.4k times · Source

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.

Answer

Michael Todd picture Michael Todd · May 15, 2010

Catch the FormClosing event and, if the reason is UserClosing, set Cancel on the event to true.

Something like the following:

Private Sub Form1_FormClosing(sender as Object, e as FormClosingEventArgs) _ 
     Handles Form1.FormClosing

    if e.CloseReason = CloseReason.UserClosing then
        e.Cancel = true
        Me.Hide()
    end if

End Sub