views:

124

answers:

3

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.

Thanks as always!

+1  A: 

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.

Matthew Scharley
Matthew, I think that's it, if I replace "Disposed" with "IsDisposed." I tried that and it worked.
John at CashCommons
Ah, remembering names, the bane of every coder....
Matthew Scharley
+2  A: 

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
Michael Todd
Thanks for responding Michael!
John at CashCommons
A: 

Agree with handling the FormClosing event. Or change the properties on the form to hide the system X control.

robert mcbean