tags:

views:

364

answers:

3

I know that in C#, there are several built in events that pass a parameter ("Cancel") which if set to true will stop further execution in the object that raised the event.

How would you implement an event where the raising object was able to keep track of a property in the EventArgs?

Here is a WinForms example of what I am trying to do:
http://msdn.microsoft.com/en-us/library/system.componentmodel.canceleventargs.cancel.aspx

Thank you.

+1  A: 

Easy:

  1. Create an instance of CancelEventArgs (or your custom type).
  2. Raise the event, passing that instance.
  3. Check the Canceld property on [1].

Do you need code samples?

Jonathan Allen
+4  A: 

It's really easy.

private event _myEvent;

// ...

// Create the event args
CancelEventArgs args = new CancelEventArgs();

// Fire the event
_myEvent.DynamicInvoke(new object[] { this, args });

// Check the result when the event handler returns
if (args.Cancel)
{
    // ...
}
Jon Seigel
Pretty obvious. It's been one of those days. Thank you very much.
Sako73
@sako73: You're welcome. We all have those days. ;)
Jon Seigel
A: 

You have to wait the call that raise the event and then check the flag in your EventArgs (in particular CancelEventArgs).

Maurizio Reginelli