Exit Box

TommyEvans

Active member
Joined
Feb 19, 2010
Messages
39
Programming Experience
Beginner
Alright. I need a box to pop up, when a user presses "Close"

It will then say "Are you sure you wish to close this program?"

and give a Yes or No option. If Yes is pressed, it will close the application. If No is pressed, it will close the popup box and the program will remain running.

I have an idea on how to do this, but I'm not exactly sure.
 
Use the FormClosing event:

VB.NET:
	Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
		Dim ans As Integer
		ans = MessageBox.Show("Are you sure you want to exit?", "Exiting", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
		If ans = 6 Then
			e.Cancel = False
		Else
			e.Cancel = True
		End If
	End Sub
 
Simpler version:

VB.NET:
'form closing event
If MessageBox.Show("Are you sure you want to exit?", "Exiting", _
   MessageBoxButtons.YesNo, MessageBoxIcon.Question) = _
   Windows.Forms.DialogResult.No Then
   e.Cancel = True
End If
 
In button31's click just call Me.Close, with the above code. Or use the above code in the click event and check for the Yes response then call Me.Close instead of e.Cancel .
 
You should also check that e.CloseReason = CloseReason.UserClosing.
VB.NET:
If e.CloseReason = CloseReason.UserClosing Then
    e.Cancel = (MessageBox.Show("Sure?", "app closing", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.Cancel)
End If
TommyEvans said:
I need this to do it on Button31.Click.
Perhaps it would be better if you named this contol for example "ExitButton" ?
In button31's click just call Me.Close, with the above code. Or use the above code in the click event and check for the Yes response then call Me.Close instead of e.Cancel .
Using the FormClosing event (and calling Close from Button) allow you to handle with same response when user clicks the forms X control button also. Or when user close from taskbar button. Or in the event that external app ask this one to close.
 
Back
Top