CancelEventArgs Class
Assembly: System (in system.dll)
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.
Note: |
|---|
| The HostProtectionAttribute attribute applied to this class has the following Resources property value: SharedState. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes. |
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 Load method of your form. Private Sub OtherInitialize() ' Exchange commented line and note the difference. Me.isDataSaved = True 'Me.isDataSaved = False End Sub 'OtherInitialize 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.") Else e.Cancel = False MessageBox.Show("Goodbye.") End If End Sub 'Form1_Closing
// 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)) {
e.set_Cancel(true);
MessageBox.Show("You must save first.");
}
else {
e.set_Cancel(false);
MessageBox.Show("Goodbye.");
}
} //Form1_Cancel
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.
Note: