Phillip Schmidt
Phillip Schmidt

Reputation: 1

Close window C#

I have a window that has a button and the button is just supposed to create a window and then delete it. The variable online is initialized to false.

private void button2_Click(object sender, EventArgs e)
{
    ZeitenZeiger zeiten = new ZeitenZeiger();
    if (!online)
    {
        zeiten.Show();
        zeiten.ShowInTaskbar = false;
        online = true;
    }
    else
    {
        zeiten.Close();
        online = false;
    }
} 

Thanks for your help.

Upvotes: 0

Views: 92

Answers (1)

Grisgram
Grisgram

Reputation: 3253

You create a new instance of zeiten every time the button is clicked.

So your .Close call calls another zeiten than your .Show opened.

Solve this by declaring zeiten on class level, and avoid closing it, instead hide it:

ZeitenZeiger zeiten = new ZeitenZeiger();
private void button2_Click(object sender, EventArgs e)
{
    if (!online)
    {
        zeiten.Show();
        zeiten.ShowInTaskbar = false;
    online = true;
    }
    else
    {
        zeiten.Hide();  // <-- Change close to hide!
        online = false;
    }
} 

Upvotes: 2

Related Questions