CancelEventArgs.Cancel Property
.NET Framework 4
Gets or sets a value indicating whether the event should be canceled.
Assembly: System (in System.dll)
The following example uses CancelEventArgs and a CancelEventHandler to handle the FormClosing 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; MessageBox.Show("Goodbye."); } }
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.