PacorrOz
PacorrOz

Reputation: 31

Prevent form from closing

I need to "disable" the X button so it just sends a message asking you to close from other button I made.

I tried this:

Private Sub Form2_Closing(sender As Object, ByVal e As CancelEventArgs) Handles MyBase.Closing
    e.Cancel = True
    MessageBox.Show("Cierra Usando el boton SALIR", "Atención", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Me.Close()
End Sub

But now I'm unable to close the form

Upvotes: 2

Views: 66

Answers (1)

LarsTech
LarsTech

Reputation: 81675

You'll need a variable:

Private okToClose As Boolean = False

Set it when the user clicks the Close button:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
  okToClose = True
  Me.Close()
End Sub

Then inspect the value:

Protected Overrides Sub OnFormClosing(e As FormClosingEventArgs)
  If Not okToClose Then
    MessageBox.Show("Cierra Usando el boton SALIR", "Atención",
                    MessageBoxButtons.OK, MessageBoxIcon.Error)
    e.Cancel = True
    MyBase.OnFormClosing(e)
  End If
End Sub

Upvotes: 1

Related Questions