关闭事件处理程序C#

时间:2012-12-07 12:41:18

标签: c# forms formclosing

我有两种形式,表格2继承自表格1。

我需要做的是,当我关闭表单1和表单2时,会出现另一个表单,询问用户是否确定要退出。然后,如果用户单击是,则当且仅当用户关闭的表单是表单2而不是表单1时,才会出现另一个询问用户是否要保存游戏的表单,因为对于表单1,无需保存。

这就是我设法做的事情:

//这些是Form 1关闭和关闭事件处理程序:

private void GameForm_FormClosing(object sender, FormClosingEventArgs e)
{
    e.Cancel = true;
    SureClose sc = new SureClose();
    sc.StartPosition = FormStartPosition.CenterScreen;
    sc.Show();
}

private void GameForm_FormClosed(object sender, FormClosedEventArgs e)
{
    MainMenu menu = new MainMenu();
    menu.Show();
}

然后在Sure Close://请注意,锦标赛是从GameForm继承的表格2(表格1)

 private void yesButton_Click(object sender, EventArgs e)
 {
        this.Hide();

        if (GameForm.ActiveForm is Tournament)
        {
            SaveGame sg = new SaveGame();
            sg.StartPosition = FormStartPosition.CenterScreen;
            sg.Show();
        } 
        else 
        {
            GameForm.ActiveForm.Close();
        }
    }

    private void noButton_Click(object sender, EventArgs e)
    {
        this.Hide();
    }

//这是SaveGame表格:

 private void saveButton_Click(object sender, EventArgs e)
 {
     // Still to do saving!
 }

 private void dontSaveButton_Click(object sender, EventArgs e)
 {
     this.Hide();
     GameForm.ActiveForm.Close();
 }

问题是当在SureClose Form中的yesButton事件处理程序中我有GameForm.ActiveForm.Close()时,这将返回到GameForm Closing事件处理程序,因此SureClose对话框再次出现。

我尝试过:if(e.CloseReason()== CloseReason.UserClosing) 但显然它不起作用,因为关闭的原因总是用户:/

我该如何解决这个问题? 非常感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

Form1:

private void GameForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if(SureClose())
    {
        SaveChanges();
    }
    else
    {
        e.Cancel = true; 
    }
}

private bool SureClose()
{
    using(SureClose sc = new SureClose())
    {
        sc.StartPosition = FormStartPosition.CenterScreen;
        DialogResult result = sc.ShowDialog();
        if(result == DialogResult.OK)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

protected virtual void SaveChanges()
{
}

窗体2:

protected override void SaveChanges()
{
    using(SaveGame sg = new SaveGame())
    {
        sg.StartPosition = FormStartPosition.CenterScreen;
        DialogResult result = sg.ShowDialog();
        if(result == DialogResult.OK)
        {
            //saving code here
        }
    }
}

SureClose表单和SaveGame表单:

private void yesButton_Click(object sender, EventArgs e)
{
    this.DialogResult = DialogResult.OK;
}

private void noButton_Click(object sender, EventArgs e)
{
    this.DialogResult = DialogResult.Cancel;
}