Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close Form Button Event

Tags:

c#

winforms

in my application, the user is first presented with the log in screen, and the form that shows up after you log in has a Menu Bar. On that menu bar are 2 items: "log out" and "exit". If the user selects the log out option, I want it to return to the aforementioned log in screen. If the user instead decided to click "exit", I prompt the user if they are sure they want to exit. Unfortunately, when the user decides to close the program by clicking the "X" button on the window, it closes only the current form. My intention would be for it to close the entire Application.

Basically, I need to know how to exit the current application by intercepting the form closing event.

Under Logout item Strip Code Is :

 private void logoutToolStripMenuItem_Click(object sender, EventArgs e)
 {
     Form_Login log = new Form_Login();
     this.Close();
     log.Show();
 }

Under The Exit item Strip Code Is :

 private void exitToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (MessageBox.Show("Are You Sure To Exit Programme ?","Exit",MessageBoxButtons.OKCancel)== DialogResult.OK)
     {
         Application.Exit();
     }
 }

And When I Click Exit Button It Close The Current Form and I Want To Close The Whole Application

like image 366
Muhammed Salah Avatar asked Jul 22 '13 19:07

Muhammed Salah


2 Answers

This should handle cases of clicking on [x] or ALT+F4

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
   if (e.CloseReason == CloseReason.UserClosing)
   {
      DialogResult result = MessageBox.Show("Do you really want to exit?", "Dialog Title", MessageBoxButtons.YesNo);
      if (result == DialogResult.Yes)
      {
          Environment.Exit(0);
      }
      else 
      {
         e.Cancel = true;
      }
   }
   else
   {
      e.Cancel = true;
   }
}   
like image 70
JBelter Avatar answered Oct 21 '22 09:10

JBelter


If am not wrong

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
   //You may decide to prompt to user
   //else just kill
   Process.GetCurrentProcess().Kill();
} 
like image 31
Sriram Sakthivel Avatar answered Oct 21 '22 08:10

Sriram Sakthivel