从已在Form1中打开的Form3关闭Form2



所以,我正在做一个小游戏。"Game.cs"打开Win屏幕("winscreen.cs")。Win屏幕使您能够创建新游戏。Game.cs是通过主菜单打开的。

如果你点击Winsscreen上的新游戏按钮,它会打开一个新的游戏场:

private void winscreen_again_Click(object sender, EventArgs e)
{
    Game loadGame = new Game();
    loadGame.Show();
}

问题是:它打开了新的游戏场,而曾经通过主菜单打开的旧游戏场仍然打开。所以我尝试了loadGame.Close();,它没有任何作用。

我在Form1.cs(主菜单):中也尝试过这样做

public Game loadGame;

稍后再调用:

this.loadGame = new Game();   
this.loadGame.StartPosition = FormStartPosition.CenterScreen;
this.loadGame.Show();

要从Winscreen.cs关闭窗口,我在Winscreen:中这样做

Game.loadGame.Close();

因为这不起作用,我做了

Game closeGame = new Game();
closeGame.loadGame.Close();

但这也不起作用,如果我将public Game loadGame;设置为"静态",this.loadGame…将不再起作用。

那么,我如何通过我的Winscreen.cs关闭现有的Game.cs呢?谢谢

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
}

在CheckWinner方法中的Game.cs中,您可以这样调用Winscreen:

//Shows the winner Animation and changes the Text to the Winning player
Winscreen loadWinscreen = new Winscreen(this);

不幸的是,我现在无法测试它来验证它是否有效。这也不是最干净的解决方案。2.nd选项:我建议使用布尔属性repeatGame,当用户按下winscreen_again按钮时,该属性可以在Winscreen.cs中设置为true。在Game.cs中创建类型为Winscreen的属性,并在Game的构造函数中订阅Closing事件。在事件处理程序中,您可以询问repeatGame标志是否已设置,如果已设置,您可以清空游戏场地并开始新游戏。

最新更新