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?

4.8
(6)

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.

How useful was this post?

Click on a star to rate it!

Average rating 4.8 / 5. Vote count: 6

No votes so far! Be the first to rate this post.

As you found this post useful...

Share this post on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?