Dooms101
Dooms101

Reputation: 492

How to intercept an Exit event for a Windows Form in VB?

When a user clicks on the little red "x" a.k.a. the form close button on the form command bar, what even is activated besides FormClosed()

I know FormClosing() is called, but I cannot really stop the form from closing after my code is run. I want to be able to show a messagebox that asks if the user wants to exit the form or not. Obviously if they click no, I want the form to stay open, how would I do this?

Upvotes: 2

Views: 6579

Answers (1)

user113476
user113476

Reputation:

In the FormClosing event you can set the Cancel property of the FormClosingEventArg to cancel the event.

    Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing

        Dim result As DialogResult = MessageBox.Show("Close Form?", "Yeehaw!", MessageBoxButtons.YesNo)
        If result = Windows.Forms.DialogResult.No Then
            e.Cancel = True
        End If

    End Sub

Upvotes: 5

Related Questions