You are currently viewing How to prevent Message Box from appears twice in FormClosing Event in C# Window Application?
C # Programming

How to prevent Message Box from appears twice in FormClosing Event in C# Window Application?

How to prevent Message Box from appears twice in FormClosing Event in C# Window Application?

In Window Form Application, We need to display confirm closing message to the user before closing the application so that the user can cancel the closing event if it is mishappened.

Here is the code to prevent Message Box from appears twice in FormClosing Event in C# Window Application.

private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                DialogResult isYes = MessageBox.Show("Are you sure you want to close the application?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                if (isYes == DialogResult.Yes)
                {
                    try
                    {
                        Application.Exit();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Problem while closing the application. Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    }

                }
                else
                {
                    e.Cancel = true;
                }
            }
        }

Hope this helps. Don’t forget to share your review and share this post to help others.