user12874458
user12874458

Reputation:

How to Override standard close (X) button in a Windows Form

How do I go about changing what happens when a user clicks the close (red X) button in a Windows Forms application (in C#)? I want to add a simple DialogResult and Messagebox to ask user if he's sure about closing the form.

Upvotes: 1

Views: 590

Answers (1)

Julius
Julius

Reputation: 187

You should handle the FormClosing event on the Form class. In the handler, you are able to set the value of the CancelEventArgs.Cancel property to true to prevent closure of the form.

Example:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("Close?", "Close", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                e.Cancel = true;
        }

You can create the handler method by double-clicking the event in the Properties tab while the Windows Forms designer is open:

FormClosing Event in Properties Tab

See https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.form.formclosing?view=windowsdesktop-6.0

Upvotes: 3

Related Questions