CancelEventArgs.Cancel 屬性


取得或設定值,這個值表示是否應該取消事件。Gets or sets a value indicating whether the event should be canceled.

 property bool Cancel { bool get(); void set(bool value); };
public bool Cancel { get; set; }
member this.Cancel : bool with get, set
Public Property Cancel As Boolean



如果應該要取消事件則為 true,否則為 falsetrue if the event should be canceled; otherwise, false.


下列範例會使用 CancelEventArgsCancelEventHandler 來處理的 FormClosing 事件 FormThe following example uses CancelEventArgs and a CancelEventHandler to handle the FormClosing event of a Form. 這段程式碼假設您已 Form 使用名為的類別層級變數來建立 Boolean isDataSavedThis code assumes that you have created a Form with a class-level Boolean variable named isDataSaved. 它也假設您已新增語句,以在 OtherInitialize 呼叫) 之後,從表單的 Load 方法或 (函式叫用方法 InitializeComponentIt also assumes that you have added a statement to invoke the OtherInitialize method from the form's Load method or the constructor (after the call to InitializeComponent).

   // Call this method from the InitializeComponent() method of your form
   void OtherInitialize()
      this->Closing += gcnew CancelEventHandler( this, &Form1::Form1_Cancel );
      this->myDataIsSaved = true;

   void Form1_Cancel( Object^ /*sender*/, CancelEventArgs^ e )
      if ( !myDataIsSaved )
         e->Cancel = true;
         MessageBox::Show( "You must save first." );
         e->Cancel = false;
         MessageBox::Show( "Goodbye." );
// Call this method from the constructor of your form
    private void OtherInitialize() {
       this.Closing += new CancelEventHandler(this.Form1_Closing);
       // Exchange commented line and note the difference.
       this.isDataSaved = true;
       //this.isDataSaved = false;

    private void Form1_Closing(Object sender, CancelEventArgs e) {
       if (!isDataSaved) {
          e.Cancel = true;
          MessageBox.Show("You must save first.");
       else {
          e.Cancel = false;
' Call this method from the Load method of your form.
Private Sub OtherInitialize()
    ' Exchange commented line and note the difference.
    Me.isDataSaved = True
    'Me.isDataSaved = False
End Sub

Private Sub Form1_Closing(sender As Object, e As _
   System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
    If Not isDataSaved Then
        e.Cancel = True
        MessageBox.Show("You must save first.")
        e.Cancel = False
    End If
End Sub