Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.form.formclosing?view=windowsdesktop-6.0

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading