簡體   English   中英

c# WinForms 表單在 Form_FormClosing 事件中設置 e.Cancel = true 后仍然關閉

[英]c# WinForms form still closes after setting e.Cancel = true in Form_FormClosing event

這是有問題的代碼:

    private void FormAccounting_FormClosing(object sender, FormClosingEventArgs e)
    {
        Properties.Settings.Default.FormAccountingLocation = this.Location;
        Properties.Settings.Default.Save();
        if (IsEditing)
        {
            MessageBox.Show("Please save or cancel open transactions before closing the accounting window.", "Open Transactions", MessageBoxButtons.OK, MessageBoxIcon.Information);
            e.Cancel = true;
        }
    }

我在e.Cancel = true;中添加了斷點。 行以確保它正在執行。

單擊確定后表單立即關閉。

下面是調用 FormAccounting 的代碼:

    private void buttonAccounts_Click(object sender, EventArgs e)
    {
        FormAccounting NewFormAccounting = new FormAccounting();
        NewFormAccounting.Show();
    }

取消表單關閉事件可以防止:

  1. 用戶關閉表單
  2. Application.Exit 退出應用程序
  3. 在表單上調用 Form.Close 的代碼

但它不能防止:

  1. 用戶關閉應用程序的主窗體
  2. 在表單上調用 Form.Dispose 的代碼
  3. 在應用程序的主 window 上調用 Form.Close 的代碼

最后 3 種情況甚至不會觸發非主表單上的表單關閉事件,因此表單會消失而沒有機會取消它。 也許您的應用程序導致表單首先以觸發事件的前 3 種方式之一關閉,然后以后 3 種方式(或類似方式)之一關閉,這不會觸發事件並強制關閉表單.

編輯:將此 function 添加到您的表單代碼中,它將允許您在調試器中查看當您的 window 關閉時調用堆棧的樣子,這樣您就可以看到實際導致它的原因:

  protected override void DestroyHandle()
  {
     System.Diagnostics.Debugger.Break();
     base.DestroyHandle();
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM