I am coding Winforms in C#. I want to set up my program so that if a form is closed, the program will terminate or stop. I already know how to select a form that will be opened first.
This is the code in my program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace MainMenu
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Login());
}
}
}
I want to set up my login.cs form so that if that form is closed, the program will terminate. Is this possible?
`
To do something when a form is closed, you need to handle the FormClosing event. Within your event handler, call Application.Exit()
to terminate the application.
Using the model in the answer linked above (but in C#), use this event handler:
private void Form_Closing(Object sender, FormClosingEventArgs e)
{
Application.Exit();
}
To add the handler, simply register the method to the event as such in your form class (based on this discussion from MSDN):
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(Form_Closing);