TaW
TaW

Reputation: 54433

Override a Control's events from a helper class

I know that when I subclass a Control I have the choice of overriding an event or subscribing to it:

public class myPanel : Panel 
{
    public myPanel()
    {
        this.Paint += myPanel_Paint;
    }

    void myPanel_Paint(object sender, PaintEventArgs e)
    {
        //
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
    }

}

My question is not about subclassing but about creating a helper class, to which a regular control instance can be registered. Now I can subscribe to its events:

class DrawCtl
{
   public Control CTL { get; set;}

public DrawCtl(Control Ctl) 
{
    CTL = Ctl;
    CTL.MouseMove += CTL_MouseMove;
}

void CTL_MouseMove(object sender, MouseEventArgs e)
{
    //
}

What I'd like to know is: Is it also possible to override a Control's event from the helper class?

Upvotes: 1

Views: 530

Answers (2)

Mehdi Khademloo
Mehdi Khademloo

Reputation: 2812

The OnPaint method is usually protected; all OnXXX event methods are protected, too. You can override and use it only in the derived classes; so you can't do this in a helper class...

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 941455

No, you cannot "override an event", overriding is only possible on virtual methods in a base class. The point of events is the exact opposite, breaking this kind of dependency between classes. It strongly empowers the component-based programming model of .NET. The huge advantage is that any class can subscribe the event. Ones you don't have to know about, nor have to be available yet.

They do have a disadvantage, they can easily break your class. You empower other code to mess up your painting. Which isn't your bug of course, you might however well get a support call about it :)

Which is also the reason that you should always override OnPaint() in your class, never use the Paint event. Because now you really want the coupling and be in control, reducing the odds that accidents occurs. You have a decision to make, and you should stick to it so your control behaves predictably. The choice you have to make is when to call base.OnPaint().

You have four choices. Call it first, then do your own painting. Makes you the boss, your paint is always on top. Or do your own painting, then call base.OnPaint(). Hands the baton to the client code and the "friendly" component-oriented way. Or put your foot down and don't call it at all. So no Paint event handler can mess it up. And the ultimate weapon, declare it sealed so nobody can override your OnPaint() method either. Never a surprise that way :)

Upvotes: 2

Related Questions