2010-09-17 31 views

回答

18

表單具有帶FormClosing類型的參數的事件FormClosingEventArgs。

private void Form1_FormClosing(object sender, FormClosingEventArgs e) 
{ 
    if (e.CloseReason == CloseReason.UserClosing) 
    { 
     if (MessageBox.Show(this, "Really?", "Closing...", 
      MessageBoxButtons.OKCancel, MessageBoxIcon.Question) 
      == DialogResult.Cancel) e.Cancel = true; 
    } 
} 
+0

我不想問是否真的關閉。我的表單有一個取消按鈕,並點擊取消我設置爲null將返回一個字段。從外面看,我知道當這個表單返回null時我不必做點什麼。但是當通過單擊X關閉窗體時,該字段不爲空,因此外部代碼崩潰。 – 2010-09-17 14:09:20

+1

技術上他確實回答你的問題...... – Xander 2010-09-17 14:58:22

2

你可以一起刪除'X'嗎?

一種形式的屬性是如果你想設置的返回字段設置爲null,像你一樣,當你點擊你的表格取消「控制盒」只是將其設置爲false

1

private void Form1_FormClosing(object sender, FormClosingEventArgs e) 
{ 
    if (e.CloseReason == CloseReason.UserClosing) 
    { 
     returnfield = null; 
     this.close(); 
    } 
} 
0

對於OnFormClosingFormClosingEventArgs.CloseReasonUserClosing要麼「X」按鈕或form.Close()方法。 我的解決方案:

//override the OnFormClosing event 
     protected override void OnFormClosing(FormClosingEventArgs e) 
     { 
      if (e.CloseReason == CloseReason.ApplicationExitCall)// the reason that you need 
       base.OnFormClosing(e); 
      else e.Cancel = true; // cancel if the close reason is not the expected one 
     } 
//create a new method that allows to handle the close reasons 
     public void closeForm(FormClosingEventArgs e) 
     { 
      if (e.CloseReason == CloseReason.UserClosing) this.Close(); 
      else e.Cancel = true; 
     } 

    //if you want to close the form or deny the X button action invoke closeForm method 
    myForm.closeForm(new FormClosingEventArgs(CloseReason.ApplicationExitCall, false)); 
           //the reason that you want ↑ 

在這個例子中的關閉(X)按鈕不關閉窗體