Frage

I have 2 forms (main and login). I open the login form with this piece of code:

toolStripProgressBar1.Value = 50;
toolStripStatusLabel_dynamic.Text = "Proberen toegang te verkrijgen...";
Login login = new Login();
login.ShowDialog();
do_login();

And I have a toolstrip menu at the top of the login form with an eventhandler like this:

private void afsluitenToolStripMenuItem_Click(object sender, EventArgs e) {
    Application.Exit();
}

But after both forms are closed, the program continues to work (it calls the function do_login.) But the variables aren't set, and the form is gone, so do_login won't work at all...

So how will I make the whole execution of the program stop when I click the toolstrip?

War es hilfreich?

Lösung

You're going to have to work around it because the definition of Application.Exit() is as follows.

Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.

So what it's saying is once all messages have been fully processed it will exit, but since you have a message that needs processed after the dialog closes it has to finish that first. You are doing the exit properly, but you're going to have to check for null and return if it is null in the do_Login() method.

Andere Tipps

Maybe check the result of ShowDialog ?

using(var login = new Login()) {
    if(login.ShowDialog() == DialogResult.OK) {
        do_login();
    }
}

(the using is because you are responsible for calling Dispose() if you use ShowDialog(), but not when you call Show())

Combined with Marc's answer, change Application.Exit to Environment.Exit(0).

private void afsluitenToolStripMenuItem_Click(object sender, EventArgs e) { 
    Environment.Exit(0);
}

I don't think calling Application.Exit(); is a good way to exit. For one, it may not allow any other code to execute that may have been put in place to clean up on application shut down.

Instead you should return a DialogResult from Login to indicate that a close is required. The main form should then check for this and close down gracefully.

try this. Environment.Exit(0);

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top