Click here to Skip to main content
15,891,828 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Guys,

Can I ask if someone have an idea on how can I write a code in the close button in the form.

Example, if the user click the close button (the red box with X) sho message.box : are you sure to exit yes/NO.

Thanks!
Posted

Handle the FormClosing event:
C#
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
    {
    if (MessageBox.Show("Are you sure?", "Close", MessageBoxButtons.YesNo) == DialogResult.No)
        {
        e.Cancel = true;
        }
    }
 
Share this answer
 
C#
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
      {

          var str = MessageBox.Show("exit", "", MessageBoxButtons.YesNo).ToString();

          if (str == "Yes")
              this.Close();
          else
              e.Cancel = true;

      }
 
Share this answer
 
v2
Comments
siasalar 1-Dec-12 6:00am    
tnx alot dude.
At the event of FormClosing add the following code

C#
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult.No == MessageBox.Show("are you sure to exit", "Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk))
            {
                e.Cancel = true;
            }

        }
 
Share this answer
 
Comments
siasalar 1-Dec-12 6:00am    
thank's a lot
DialogResult dialogResult = MessageBox.Show("Are you Sure to Delete Record...", "Employee Info...", MessageBoxButtons.YesNo);
 if (dialogResult == DialogResult.Yes)
            {
This.close();
}
 
Share this answer
 
v2
Hi dear,
See this code.

C#
DialogResult a ;
a = MessageBox.Show("Are you sure to exit.","Message" , MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
if (a == DialogResult.Yes)
{
    Close();
}
else
{
   // Continue your desire work
}
 
Share this answer
 
v2

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