Click here to Skip to main content
15,889,784 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have build one small Win Form App with Threading. While processing the application if user clicked Close button on the Form then i must show warning Message box.

I have written below code and it is working fine. But problem is "Message box appears twice". How to overcome this.

C#
private void frmTranxitCCTVJobCreation_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason != CloseReason.UserClosing)
                return;
            if (bIsButtonClicked == true)
            {
                if (_threadProcessCCTV.IsAlive)
                {
                    if (MessageBox.Show("Are you sure you want to close the form?", "Warning", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                        e.Cancel = false;
                    else
                        // Cancel the Closing event from closing the form.
                        e.Cancel = true;
                }
            }
        }
Posted
Updated 4-Sep-19 8:51am
Comments
jackspero18 23-Dec-13 3:07am    
Did you Tried...???
mn.sathish 23-Dec-13 3:15am    
Ya...., I have done. Its working fine. Thanks for your help

try this

C#
if(e.CloseReason == CloseReason.UserClosing)
            {
                dynamic result = MessageBox.Show("Do You Want To Exit?", "Application Name", MessageBoxButtons.YesNo );
                if (result == DialogResult.Yes )
                {
                    Application.Exit();
                }
              
                if (result == DialogResult.No)
                {
                    e.Cancel = true;
                }
            }
 
Share this answer
 
v2
DialogResult dialogResult = MessageBox.Show("Are you sure, you want to exit ?                  ", "Application Name", MessageBoxButtons.YesNo);

          if (dialogResult == DialogResult.Yes)
          {
              if (Application.OpenForms.Count == 0)
                  Application.Exit();
          }
          else if (dialogResult == DialogResult.No)
          {
              e.Cancel = true;
          }
 
Share this answer
 
Comments
CHill60 5-Sep-19 6:25am    
You will still get the message twice because you have not interrogated the reason for closing.
If the number of OpenForms is not 0 (which it won't be) then you will still exit the application - follow the code through.
Apart from these obvious errors, a code dump on an already answered post from 6 years ago is only going to attract downvotes and reports - you need to explain why your solution is better or different to the one already posted. You also need to make sure it works.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900