Form.OnClosing(CancelEventArgs) 方法

定義

引發 Closing 事件。

C#
protected virtual void OnClosing(System.ComponentModel.CancelEventArgs e);

參數

e
CancelEventArgs

CancelEventArgs,其中包含事件資料。

範例

下列範例會使用 Closing 來測試 中的 TextBox 文字是否已變更。 如果有,系統會詢問使用者是否要將變更儲存至檔案。

C#
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
   // Determine if text has changed in the textbox by comparing to original text.
   if (textBox1.Text != strMyOriginalText)
   {
      // Display a MsgBox asking the user to save changes or abort.
      if(MessageBox.Show("Do you want to save changes to your text?", "My Application",
         MessageBoxButtons.YesNo) ==  DialogResult.Yes)
      {
         // Cancel the Closing event from closing the form.
         e.Cancel = true;
         // Call method to save file...
      }
   }
}

備註

注意

從 .NET Framework 2.0 開始,方法 OnClosing 已過時;請改用 OnFormClosing 方法。

引發事件會透過委派叫用此事件處理常式。 如需詳細資訊,請參閱 處理和引發事件

OnClosing 方法也允許衍生類別處理事件,而不用附加委派。 覆寫此方法是處理衍生類別中事件慣用的技術。

注意

OnClosed呼叫 方法以結束應用程式時 Application.Exit ,不會呼叫 和 OnClosing 方法。 如果您在其中一個必須執行的方法中有驗證程式代碼,您應該先個別呼叫 Form.Close 每個開啟表單的方法,再呼叫 Exit 方法。

給繼承者的注意事項

當在衍生類別中覆寫 OnClosing(CancelEventArgs) 時,請確定呼叫基底類別的 OnClosing(CancelEventArgs) 方法,使已註冊的委派能接收到事件。

適用於

產品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9

另請參閱