How to prevent Message Box from appears twice in FormClosing Event in C# Window Application?
When you are working with the window form application you may be facing the issue of Message Box that 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.