CancelEventArgs Class

Provides data for a cancelable event.

Namespace: System.ComponentModel
Assembly: System (in system.dll)

public class CancelEventArgs : EventArgs
public class CancelEventArgs extends EventArgs
public class CancelEventArgs extends EventArgs
Not applicable.

A cancelable event is raised by a component when it is about to perform an action that can be canceled, such as the Closing event of a Form.

A CancelEventArgs provides the Cancel property to indicate whether the event should be canceled.

The following example uses a CancelEventArgs and a CancelEventHandler to handle the Closing event of a Form. This code assumes that you have created a Form with a class-level Boolean variable named isDataSaved. It 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 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;

// Calls this method from the InitializeComponent() method of your form
private void OtherInitialize()
    this.add_Closing(new CancelEventHandler(this.Form1_Cancel));
    this.myDataIsSaved = (boolean)new System.Boolean();
    this.myDataIsSaved = true;
} //OtherInitialize

protected void Form1_Cancel(Object sender, CancelEventArgs e)
    if (!(myDataIsSaved)) {
        MessageBox.Show("You must save first.");
    else {
} //Form1_Cancel

       Derived Classes

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

XNA Framework

Supported in: 1.0