Closing() with CancelEventArgs versus Form_Closing with Form

本文关键字:Form Closing with versus CancelEventArgs | 更新日期: 2023-09-27 18:16:21

我们目前正在升级和重新调整我们的代码,因为我们从32位系统转移到64位系统。在适当的过程中,我们的目标之一是改变Init()函数,其中添加的东西就像这样。

this.Closing += new System.ComponentModel.CancelEventHandler(this.Form_Closing);

我希望Windows事件能够处理这些事情。所以我去了Windows窗体事件中的Form_Closing事件,毫无意外地发现这不是Form_Closing事件。我的问题是,有什么是实际发生与CancelEventArgs与FormClosingArgs之间的区别,或者这两段代码字面上做同样的事情一个是系统的组件和一个是Windows事件处理的结果它做得最好?作为一名实习生,我只是沉浸在这个新项目中。是否有可能用FormClosing代替CancelEventArgs而没有任何数据丢失或问题?

代码1:CancelArgs
 private void Form_Closing(object sender, CancelEventArgs e)
    {
        // If the user hit Cancel, just close the form.
        if (this.DialogResult == DialogResult.Ignore)
            return;
        if (this.DialogResult == DialogResult.OK)
        {
            // If the address is not dirty, just cancel out of
            // the form.
            if (!this._editedObject.IsDirty)
            {
                this.DialogResult = DialogResult.Cancel;
                return;
            }
            // Save changes.  If save fails, don't close the form.
            try
            {
                SaveChanges();
                return;
            }
            catch (Exception ex)
            {
                ShowException se = new ShowException();
                se.ShowDialog(ex, _errorObject);
                _errorObject = null;
                e.Cancel = true;
                return;
            }
        }

Form_Closing—Preferred Route

private void ScheduleItemDetail_FormClosing(object sender, FormClosingEventArgs e)
    {
        // If the user hit Cancel, just close the form.
        if (this.DialogResult == DialogResult.Ignore)
            return;
        if (this.DialogResult == DialogResult.OK)
        {
            // If the address is not dirty, just cancel out of
            // the form.
            if (!this._editedObject.IsDirty)
            {
                this.DialogResult = DialogResult.Cancel;
                return;
            }
            // Save changes.  If save fails, don't close the form.
            try
            {
                SaveChanges();
                return;
            }
            catch (Exception ex)
            {
                ShowException se = new ShowException();
                se.ShowDialog(ex, _errorObject);
                _errorObject = null;
                e.Cancel = true;
                return;
            }
        }
    }

Closing() with CancelEventArgs versus Form_Closing with Form

你不会从CancelEventArgs类中获得CloseReason属性,这是唯一的区别,因为FormClosingEventArgs继承自CancelEventArgs类。FormClosingEventArgs是在。net 2.0中引入的。

或者,不使用事件,你也可以重写OnFormClosing方法。

protected override void OnFormClosing(FormClosingEventArgs e) {
  // your code
  base.OnFormClosing(e);
}