Search code examples
vb.netformclosing

Skip Me.FormClosing


i've set a warning message before closing the form, but is there a way to skip it sometimes?

My code:

Sub Me_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    If MessageBox.Show("Are you sure you want to cancel the installation?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
        e.Cancel = False
    Else
        e.Cancel = True
    End If
End Sub

but i have a final code that must close the app without this message:

Private Sub Done_Click(sender As Object, e As EventArgs) Handles Done.Click
    'need to close without warning
    Close()
End Sub

can you help me change this or add something that allows that button to close the form without launching Me.FormClosing?


Solution

  • Use a Boolean flag to determine the installation status (success or fail/abort)

    Private installSuccess As Boolean ' False by default.
    
    Private Sub Install()
    
        Try 
            ' Installer logic here
            ' ...
    
            Me.installSuccess = True
    
        Catch ' ex As Exception
    
        End Try
    
    End Sub
    

    Then:

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) _
    Handles MyBase.FormClosing
    
        If Me.installSuccess Then
            Exit Sub
        End If
    
        If MessageBox.Show("Are you sure you want to cancel the installation?", "Warning", 
                           MessageBoxButtons.YesNo, 
                           MessageBoxIcon.Question) = DialogResult.Yes Then
            e.Cancel = False
    
        Else
            e.Cancel = True
    
        End If
    
    End Sub