Hello there fellow members.

I have two windows forms, and they call each other.
- Form 1 has a button that calls Form 2.
- Form 2 does not have an exit button, but rather a button that goes back to Form 1.
- Form 1 is the main form and the program is terminated from it.

Now, I have a background algorithm in Form 1 which must not work when going to Form 2, but when I go back from 2 to 1, that algorithm should work again.

So, I did the following:

- Code of the button that takes me from Form 1 to 2:

Form2 frm2 = new Form2();
       
       frm2.Show();
       this.Hide();

- Code of the button that takes me back from 2 to 1:

Form1 frm1 = new Form1();
            this.Close();
            
            frm1.Show();

However, this leads to a problem of Form replication. If I go through the forms back and forth a little bit, then back to the main form and close the application; some artifacts remain in the background. Instances of the application itself remain working (can be shut off from the Task Manager), so how do I make sure that once Form 1 is closed, the application and all extra instances created during this Form traversal are terminated?

Thanks in advance!

When creating Form 1, use this method:

Application.Run(new Form1());

This should set Form 1 as the main window of the program, and should terminate the program when it is closed.
Note: This calls the ShowDialog() method of the form after the constructor.

I am using this line in my Program.cs file, but artifacts of Form1 still remain in the background after I go back from Form 2 to Form1.

Just to clarify, Form 1 is indeed the main window and the program terminates when it is closed; IF I close it before going back and forth between Form1 and Form2 (Going back between them creates hidden Form1 instances).

Hi
When you want to open the form 2 pass an instance of form1 in the form 2 constructor.ie in the button that shows form2 code should be;

Form2 frm2 = new Form2(this);
       
       frm2.Show();
       this.Hide();

In the form 2 constructor get that instance of form1 an asign it to a variable of type Form1 ie in Form2;

Form1 = MainForm
 public Form2(Form1 InputForm)
{
MainForm = InputForm;
}
Then in the button that takes you to Form1 insert foll code
MainForm.Show();

Ah, yes. I never thought about passing Form1 to 2.

I tried it, and it works.

Thanks guys!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.