EyeSeeSharp
EyeSeeSharp

Reputation: 645

c# True hide form

I have 2 forms, Form1 and SlimSkin. Both have buttons to close their form and show the opposite form via:

On Form1

    private void slimbutton_Click(object sender, EventArgs e)
    {
        var slimform = new SlimSkin();
        slimform.Show();
        this.Hide();
    }

On SlimSkin

 private void button2_Click(object sender, EventArgs e)
    {
        var form1 = new Form1();
        this.Close();
        form1.Show();
    }

However, it seems likes when I open or 'show' the form, it creates a new instance of it. For example, I'd open SlimSkin and go back to form1, and if I was to close out of it/stop debugging, there's still an instance of each form running in the background so the program doesn't stop running.

I've also tried

this.Visible = false; and this.Visible = true; but it yeilded the same result.

Is there a more effective way of hiding a form and recalling the same hidden form?

Upvotes: 1

Views: 484

Answers (3)

Servy
Servy

Reputation: 203829

When your main form creates the child form, hides itself, and shows that form, have it attach a handler to the FormClosed event so that it can show itself when that form is closed:

private void slimbutton_Click(object sender, EventArgs e)
{
    var slimform = new SlimSkin();
    slimform.Show();
    slimform.FormClosed += (s, args) => this.Show();
    this.Hide();
}

When the second form closes itself it'll fire the event, which will show the main form, so the second form need only close itself:

private void button2_Click(object sender, EventArgs e)
{
    this.Close();
}

Upvotes: 1

Andrey Korneyev
Andrey Korneyev

Reputation: 26856

Indeed, you're creating new instance of Form1 and SlimSkin each time in _Click handlers.

Instead you need to add field MainForm containing current instance of Form1 into SlimSkin class and similarily field SlimForm containing instance of ClimSkin into Form1 class.

Then manipulate your forms something like:

public Form SlimForm;
private void slimbutton_Click(object sender, EventArgs e)
{
    if (SlimForm == null)
    {
        SlimForm = new SlimSkin();
        SlimForm.MainForm = this;
    }

    SlimForm.Show();
    this.Hide();
}

And then in SlimSkin:

private Form MainForm;
private void button2_Click(object sender, EventArgs e)
{
    MainForm.Show();
    this.Hide();
}

Here I assuming that SlimForm will always be called from Form1 first. If not - then field MainForm should be instantiated before using like in Form1.

Upvotes: 0

user2726374
user2726374

Reputation: 46

On each button click you are creating a new instance of other form. you can try dispose if you want to completely get rid of the instance

Upvotes: 0

Related Questions