Form.OnClosing(CancelEventArgs) 方法

定義

引發 Closing 事件。

protected:
 virtual void OnClosing(System::ComponentModel::CancelEventArgs ^ e);
protected virtual void OnClosing (System.ComponentModel.CancelEventArgs e);
abstract member OnClosing : System.ComponentModel.CancelEventArgs -> unit
override this.OnClosing : System.ComponentModel.CancelEventArgs -> unit
Protected Overridable Sub OnClosing (e As CancelEventArgs)

參數

e
CancelEventArgs

CancelEventArgs,其中包含事件資料。

範例

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

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...
         }
      }
   }
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...
      }
   }
}
   Private Sub Form1_Closing(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
      ' Determine if text has changed in the textbox by comparing to original text.
      If textBox1.Text <> strMyOriginalText Then
         ' 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 Then
            ' Cancel the Closing event from closing the form.
            e.Cancel = True
         End If ' Call method to save file...
      End If
   End Sub
End Class

備註

警告

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

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

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

警告

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

給繼承者的注意事項

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

適用於

另請參閱