views:

240

answers:

4

Hi,

Let's say I have an event. Let's call it DoStuff. Before DoStuff happens, I'm trying to use another event, PreviewDoStuff, to check if I need to prevent DoStuff from being called. The problem I'm facing with this is that I'm unable to get any kind of value back from the PreviewDoStuff, like a return code or anything due to how events are written. And event args aren't passed back to the caller, so I can't get the event args "handled" property. I'm sure there has to be a way to do it, but I'm not sure how. Any ideas?

Thanks!

+4  A: 

Declare the event as EventHandler<CancelEventArgs>. Then the listener can set Cancel to true, and you can use that value to determine whether to raise the "real" event or not.

Mandatory code sample:

public event EventHandler<CancelEventArgs> PreviewDoStuff;
public event EventHandler DoStuff;

private void RaiseDoStuff()
{
    CancelEventArgs args = new CancelEventArgs();
    OnPreviewDoStuff(args);
    if (!args.Cancel)
    {
        OnDoStuff(EventArgs.Empty);
    }
}

protected void OnPreviewDoStuff(CancelEventArgs e)
{
    EventHandler<CancelEventArgs> previewDoStuff = PreviewDoStuff;
    if (previewDoStuff != null)
    {
        previewDoStuff(this, e);
    }
}

protected void OnDoStuff(EventArgs e)
{
    EventHandler doStuff = DoStuff;
    if (doStuff != null)
    {
        doStuff(this, e);
    }
}

For an example of this in real-life use, check the FormClosing event, which uses a FormClosingEventArgs class, which in turn inherits from CancelEventArgs.

Fredrik Mörk
A: 

Have your PreviewDoStuff set an internal flag which DoStuff checks when it fires. Even better, have the code that raises DoStuff check the flag before it raises the event.

Chris B. Behrens
A: 

Can you provide some of your code how you are writing DoSTuff and PreviewDoStuff?

AppDeveloper
A: 

I assume you mean you want to create your own event called DoStuff. I think it's possible to pass "ref" arguments:

public delegate void PreviewDoStuffFunc(ref bool Handled);
public event PreviewDoStuffFunc PreviewDoStuff;

But the standard way would be to use something like CancelEventArgs:

public event CancelEventArgs PreviewDoStuff;
public event EventArgs DoStuff;

Then after you fire the preview event, you check the Cancel:

var e = new CancelEventArgs();    
if (PreviewDoStuff != null)
    PreviewDoStuff(this, e);
if (!e.Cancel)
    DoStuff(this, EventArgs.Empty);
Qwertie