VB.NET: Abort FormClosing()
Asked Answered
L

2

9

I have a code snippet that I want to run when the app is closing. So, I used FormCLosing event. But now i wanna place a confirmation message for exiting. Like, if the user clicks the Exit(X) button, there'll be a prompt, if he clicks NO, then the app will not close and revert to previous state.

Now I find that hard to achieve using FormClosing event. because it'll get executed no matter what button the user clicks. Any remedy for that?

I mean, I need an even like ExitButtonPressed()..

Libratory answered 13/2, 2010 at 7:48 Comment(0)
P
23

You could try something like

Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
    If (MessageBox.Show("Close?", "", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.No) Then
        e.Cancel = True
    End If
End Sub

Have a look at

FormClosingEventArgs Class

And

CancelEventArgs.Cancel Property

The event can be canceled by setting the Cancel property to true.

Powell answered 13/2, 2010 at 7:51 Comment(2)
Inside the FormClosing event.Vaduz
Thanx. but having another problem now. #2257409Libratory
D
0

'Button2 and closebutton of the form both closes the form asking the same 'question

Dim button2Yes As Boolean = False Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

    If MessageBox.Show("    Sure to close?   ", "CLOSING CONTROL", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
        button2Yes = True
        Me.Close()
    Else
        button2Yes = False
    End If
End Sub

Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles Me.FormClosing
    If Not button2Yes Then
        If Not MessageBox.Show("    Sure to close?   ", "CLOSING CONTROL", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
            e.Cancel = True
        End If
    End If
End Sub
Drexler answered 19/11, 2017 at 18:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.