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
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.
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--;
}
}
}
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