【问题标题】:Two different ways of handling the form Close event处理表单关闭事件的两种不同方式
【发布时间】:2016-12-04 05:40:20
【问题描述】:

我的WinForm 上有一个保存 按钮,它保存表单信息,然后使用this.Close() 语句关闭表单。

还有另一种关闭表单的方法,那就是X 按钮。

我正在使用FormClosing 事件在表单关闭之前提出问题。

private void EmailNewsletter_FormClosing(object sender, FormClosingEventArgs e)
{
    DialogResult dr = MsgBox.Show("Are you sure you want to dimiss this newsletter?", "Dismiss Newsletter", MsgBox.Buttons.YesNo, MsgBox.Icon.Question);
    if (dr == System.Windows.Forms.DialogResult.Yes)
    {
        this.Newsletter = null;
    }
    else
    {
        e.Cancel = true;
    }
}

但是处理关闭表单的方式取决于表单是如何关闭的。如果用户点击 Save 按钮,表单应该被关闭而没有问题。只有当用户点击X 按钮时才会提出问题。

如何让我的表单知道 Close 命令的来源?

【问题讨论】:

  • 使用变量“isFromSaveButton”....

标签: c# winforms events event-handling


【解决方案1】:

一个简单的布尔标志应该可以解决问题:

private bool saveClicked = false;
private void btnSave_click(object sender, EventArgs e)
{
      saveClicked = true;
}
private void EmailNewsletter_FormClosing(object sender, FormClosingEventArgs e)
{
    if(saveClicked)
         return;

    DialogResult dr = MsgBox.Show("Are you sure you want to dimiss this newsletter?", "Dismiss Newsletter", MsgBox.Buttons.YesNo, MsgBox.Icon.Question);

    if (dr == System.Windows.Forms.DialogResult.Yes)
    {
        this.Newsletter = null;
    }
    else
    {
        e.Cancel = true;
    }
}

【讨论】:

  • 谢谢!将在 5 分钟内被接受为答案,因为我提高了你!
猜你喜欢
  • 2021-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多