Search code examples
c#winformsnotificationsformclosing

C# Windows Form formclosing error


i am pretty newbie for coding. Here is i am having a problem:

private void pano_FormClosing(object sender, FormClosingEventArgs e)
    {
        DialogResult dialog = MessageBox.Show("Uygulamadan çıkış yapmak istediğinizden emin misiniz?", "Çıkış", MessageBoxButtons.YesNo);
        if (dialog == DialogResult.Yes)
        {
            Application.Exit();
        }
        else if (dialog == DialogResult.No)
        {
            e.Cancel = true;
        }

My purpose with this code block to ask user "are sure to quit" but unfortunetly when i close the application, i got notification window for 3 times? Is there any idea why thats happening or any solution?

Thanks a lot. Nuri.


Solution

  • Firstly, as Steve pointed out, remove the 'Yes' part - if not explicitly canceled, the event will close that form as a result of clicking.

    Now, for the problem of yours. Seems like your alert is called twice. I was able to solve that easily by making a static bool close_alert_shown, and when the first alert is shown, set it to true so that the next alert won't pop up.

    Final code looks like that:

                if (close_alert_shown) return;
                close_alert_shown = true;
                DialogResult dialog = MessageBox.Show("Uygulamadan çıkış yapmak istediğinizden emin misiniz?", "Çıkış", MessageBoxButtons.YesNo);
                if (dialog == DialogResult.No)
                {
                    e.Cancel = true;
                    close_alert_shown = false;
                }
    

    And on the top of the form (before the public Form1() contructor line):

        static bool close_alert_shown = false;