英語で読む

次の方法で共有


CancelEventArgs.Cancel プロパティ

定義

イベントをキャンセルするかどうかを示す値を取得または設定します。

C#
public bool Cancel { get; set; }

プロパティ値

イベントを取り消す場合は true。それ以外の場合は false

次の例では、 と をCancelEventHandler使用CancelEventArgsして のイベントをFormFormClosing処理します。 このコードでは、 という名前isDataSavedのクラス レベルBooleanの変数を使用して をForm作成していることを前提としています。 また、(の呼び出しの後に) フォームの Load メソッドまたはコンストラクターから メソッドを呼び出InitializeComponentOtherInitialize ステートメントを追加したことを前提としています。

C#
// 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;
          MessageBox.Show("Goodbye.");
       }
    }

適用対象

製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.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
.NET Standard 2.0, 2.1
UWP 10.0