Home > Back-end >  Closing the form does not closing the Application
Closing the form does not closing the Application

Time:10-30

I have two forms in my c# windows project . The first form is called is called "loginform" and the other one is called "mainform" . I want to move to the mainform on button click But when i reached at the mainform , the problem is when i tries to close my second form which is named "mainform" here , the application does not close and i have to use the visual studio to terminate the project. below is the code for moving to second form

        this.Hide();
        mainform mf = new mainform();
        mf.Show();

CodePudding user response:

I found the answer. On the second form add the following code on the formclosed event .

 private void mainform_FormClosed(object sender, FormClosedEventArgs e)
    {
        Application.ExitThread();
    }

CodePudding user response:

The problem you have is because “your code” basically “throws away” ANY reference back to this when the code sets it as “hidden”…

this.Hide();

After this line of code is executed, mainform is created and shown…

mainform mf = new mainform();
mf.Show();

Assuming, there is no code “after” the code above… then basically this has now been lost. The user can NOT see the form nor interact with it. mainform is shown… but it knows nothing about this. this is now lost and you have NO way of getting it back. That’s why it keeps running.

Obviously, mainform has no idea about this i.e. … the form that “created” it, however it DOES need this to stay alive. IF we “close” this and this created mainform… then mainform depends on this and will also close when this closes.

mainform mf = new mainform();
mf.Show();
this.Close();

Then, mainform gets killed as soon a this closes. So that will not work. However… if you changed the Show to ShowDialog… for the mf.ShowDialog(), then it would work and this would get closed properly.

Therefore, IF you want to “CLOSE” the form that “created” another form, then you should spin off another process for the mainform or pass this to the mainform and let it close it when it is done. I am sure there are other ways to do this and if Application.ExitThread(); ... works for you then go for it.

  • Related