Search code examples
c#.netwinformswindows-forms-designer

How to Prevent Multiple Confirmation Dialogs When Closing Forms in WinForms Application?


I have a WinForms application where I need to show a confirmation dialog when the form is being closed and it should close the entire application. However, the confirmation dialog appears multiple times when closing the application, which is not the desired behavior.

protected override void OnFormClosing(FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing)
    {
        DialogResult result = MessageBox.Show("Are you sure you want to close the application?", "Confirm Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

        if (result == DialogResult.No)
        {
            e.Cancel = true; // Cancel the form closing
            return;
        }
        else
        {
            // Close the entire application
            Application.Exit();
        }
    }
}

this dialog box appears two or more while close this app

This dialog box appears two or more while close this app.

  • How can I ensure that the confirmation dialog is only shown once when closing the form?

  • Is there a more effective way to handle closing multiple forms and showing the confirmation dialog only once?

  • The confirmation dialog is intended to confirm if the user wants to close the entire application.

  • There are other forms open in the application, which should also be closed when the main form closes.


Solution

  • I tried recreating the issue and your code works perfectly fine, I guess the issue lies elsewhere, was the loginform your startup form(main)?

    here's the code which is the same code as yours, however I omitted the

    Application.Exit();
    

    as it is not needed if you're actually closing the main form, however if your calling it form your child form, that will trigger the FormClosing event in other forms as well including the login(if it's not the main)

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                DialogResult result = MessageBox.Show("Are you sure you want to close the application?", "Confirm Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    
                if (result == DialogResult.No)
                {
                    e.Cancel = true; // Cancel the form closing
                    return;
                }
            }
        }
    }