Reputation: 796
So, i'm working on a little Game. The "Game.cs" opens the Win-Screen ("winscreen.cs"). The Winscreen gives you the ability to create a New Game. The Game.cs was opened trough the MainMenu.
If you click the New-Game Button on the Winscreen, it opens up a new Playfield:
private void winscreen_again_Click(object sender, EventArgs e)
{
Game loadGame = new Game();
loadGame.Show();
}
The Problem is: It opens up the new Playfield, and the old one, that once was opened trough the MainMenu stays open. So i tried loadGame.Close();
which does nothing.
I also tried to do this in my Form1.cs (The MainMenu):
public Game loadGame;
and call this later:
this.loadGame = new Game();
this.loadGame.StartPosition = FormStartPosition.CenterScreen;
this.loadGame.Show();
To close the Window from the Winscreen.cs i did this in the Winscreen:
Game.loadGame.Close();
and because that didnt worked, i did
Game closeGame = new Game();
closeGame.loadGame.Close();
but that did not work either, and if i set the public Game loadGame;
to "static" the this.loadGame... wouldnt work anymore.
So how do i close the existing Game.cs trough my Winscreen.cs? Thanks!
Upvotes: 0
Views: 93
Reputation: 23732
public partial class Winscreen : Form
{
// Variable to catch the old playfield
Game oldPlayfield;
// the old playfield is passed in the constructor
public Winscreen(Game opf)
{
this.oldPlayfield = opf;
InitializeComponent();
}
private void winscreen_again_Click(object sender, EventArgs e)
{
Game loadGame = new Game();
loadGame.Show();
// close the old field
this.oldPlayfield.Close();
}
// rest of the class
}
In Game.cs
inside the CheckWinner method you would call the Winscreen like this:
//Shows the winner Animation and changes the Text to the Winning player
Winscreen loadWinscreen = new Winscreen(this);
Unfortunately I cannot test it now to verify whether it would work.
This is also not the cleanest solution.
2.nd option:
I would suggest rather to have a boolean property repeatGame
that can be set to true in Winscreen.cs
when the user presses the winscreen_again
Button. Create a property of type Winscreen
inside Game.cs
and subscribe to the Closing
event in the constructor of Game
.
Inside the eventhandler you could ask whether the repeatGame
flag has been set and if so you could just clear the playfield and start a new game.
Upvotes: 1