Basically I have a main form which upon loading, opens a child form for logging in the user. When they cancel or close this login form, I need to close the whole application.
But there seems to be a few different ways to close a C# program:
Application.Exit();
Application.ExitThread();
Environment.Exit(1);
Process.GetCurrentProcess().Kill();
SFTPClient.LDAPLoggedIn = false; Close();
EDIT: Sorry if this one is not clear: It sets a property in a controller object to indicate that the login failed. After opening the child form, I would check this property in the parent form to see whether the program should continue or not. It basically shifts the responsibility of exiting the program to the parent without an exception.
6: throw new Exception("User closed the form");
I can see that there are two ways of handling it:
- Informing the parent that something went wrong (as in 5 and 6.)
- Closing the program from the child form.
Is either of these two considered better practice?
Each approach seems to have the same effect on my program but how do they actually compare?
UPDATE: Thanks for the answers. For those searching this question in the future and curious people, this was my solution in the end:
private void FormMain_Load(object sender, EventArgs e)
{
if (new FormLogin().ShowDialog(this) == DialogResult.Cancel) Close();
}
and:
private void buttonCancel_Click(object sender, EventArgs e)
{
Close();
}
I discovered that when a form is closed via clicking the 'X', DialogResult is set to Cancel automatically so all I need to do is Close()