Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Programming the X (close) button on a form 2

Status
Not open for further replies.

tekrobg

Programmer
Oct 12, 2004
42
US
I am new to programming. Where can I program the X (close) button on a form? I just want to put in a dialog box asking if the user is really sure they want to exit the program.

Thanks for any help.
 
Put code in the OnClosing event in the form. It has a CancelEventArgs parameter where you can tell the form not to close.

Chip H.


____________________________________________________________________
Click here to learn Ways to help with Tsunami Relief
If you want to get the best response to a question, please read FAQ222-2244 first
 
I found the OnClosing event in the Overrides section of the form (I'm assuming that's right). Here's the code I put in it:

vb/
Protected Overrides Sub OnClosing(ByVal e As System.ComponentModel.CancelEventArgs)
If MsgBox("Are you sure you want to exit?", MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Exclamation) = MsgBoxResult.Yes Then
Me.Close()
Else
Exit Sub
End If
End Sub
/vb

It does bring up the dialog box; however, the box does not work right. If I click on "yes" (to exit), nothing happens and the dialog box does not go away. If I click on "no" to NOT close the application, the application closes.

Any ideas what I'm doing wrong?

Thanks for any help.
 
If you don't want to close the form then you should add

e.Cancel = True to avoid the form close.

So it would be

Code:
Protected Overrides Sub OnClosing(ByVal e As System.ComponentModel.CancelEventArgs)

        If MsgBox("Are you sure you want to exit?", MsgBoxStyle.YesNo, MsgBoxStyle.DefaultButton2, MsgBoxStyle.Exclamation) = MsgBoxResult.No Then

             e.Cancel = True
        End If
End Sub

Note that you don't have to do anything to close the form when the user click Yes because your form is already "Closing" so no need to close a form which is already closing.

-Kris
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top