views:

88

answers:

3

Hi, the situation is like this i have a control and it has event Render in the definition of the control, to this event is attached handler i am looking for a way to show some kind of message if in some class that uses this control another handler is attached to this event Best Regards, Iordan

A: 

I'm confused.

Can you detect the calling of '+= new EventHandler ( ... )' and stop it ... what?

I think you just need to organise your code better. Or re-word your question.

Noon Silk
Think he is looking to just show a message when a handler subscribes to the Render event....don't think its possible.
James
Well may be i was a little unclear here is the situation i have my control that inherits DataGridView control i have attached Eventhandler for CellPaint event. I want if someone who uses my control attaches another eventHandler to this event to make some message that tihs can lead to different problemsBest Regards,Iordan
IordanTanev
A: 

This does not strike me as a good approach. When using events, the control should typically not be dependent on the number of event handlers attached. It should work regardless of whether there are 0 or 27 event handlers reacting on the event. If you want to have a mechanism where you have more control you should probably consider using a delegate instead.

If you for some reason are restricted to use the event model and want to have control over the assignment of event handlers, one approach might be to inherit the original class, creating an event in that class with the same name and signature as in the base class (using the new keyword so that the original event is hidden), and keep track of how event handlers are attached and detached:

public class BaseClass
{
    public event EventHandler SomeEvent;
}

public class MyClass : BaseClass
{
    private int _refCount = 0;
    public new event EventHandler SomeEvent
    {
        add
        {
            if (_refCount > 0)
            {
                // handler already attached
            }
            base.SomeEvent += value;
            _refCount++;
        }
        remove
        {
            base.SomeEvent -= value;
            _refCount--;
        }
    }
}
Fredrik Mörk
+2  A: 

dont expose the event publicly. expose it as a property. this will give you control when external classes are attaching handlers

class MyClass { private EventHandler _myEvent;

public event EventHandler MyEvent
{
    [MethodImpl(MethodImplOptions.Synchronized)]
    add 
    { 
        _myEvent = (EventHandler)Delegate.Combine(_myEvent, value);
    }
    [MethodImpl(MethodImplOptions.Synchronized)]
    remove 
    { 
        _myEvent = (EventHandler)Delegate.Remove(_myEvent, value); 
    }
}
...

}

more info on this here

http://msdn.microsoft.com/en-us/magazine/cc163533.aspx

zecougar
Think this was pretty much what he is looking for. Nice, wasn't aware you could do this sort of thing in C#
James