Eibach
Eibach

Reputation:

How to call Events in Interfaces C#?

So i have a design problem. I have a mouse class that has delegates and events. ie MouseButtonPressed, MouseMoved. and such that are getting called by a state engine.

What i want to have happen is to create an interface like IClickable or IDraggable or somthing and have events inside those interfaces that get called when the mouse event gets called.

public interface IClickable

public event MouseDevice.ButtonClickedHandler<MouseButtons, MouseState> Clicked;

then in the MouseDevice class it has

public delegate void ButtonClickedHandler<O, S>(object sender, InputDeviceEventArgs<O, S> e);

and

public event ButtonClickedHandler<MouseButtons, MouseState> ButtonClicked;

So basically I want to have Clicked be called when buttonClicked gets called.

Is there a way to do this?

Upvotes: 2

Views: 3166

Answers (2)

thecoop
thecoop

Reputation: 46108

When you declare an event inside an interface, it doesn't actually create the event that can be called - you have to then implement that event within any classes that implement the interface.

As interfaces can't contain any code, you will have to add the OnMouseClicked method (or whatever) in all your implementing classes separately to call the event in the class. You could also make OnMouseClicked an extension method on the interface itself, but that is slightly subverting what extension methods are meant for...

Upvotes: 0

Igor Zelaya
Igor Zelaya

Reputation: 4277

You mean something like this?

public class MouseDevice {
    public delegate void ButtonClickedHandler<O, E>(O sender, E e);
}

public interface IClickable<O,E> {
    event MouseDevice.ButtonClickedHandler<O,E> Clicked;
}

public class StateMachine : IClickable<Control,MouseEventArgs>
{

    public event MouseDevice.ButtonClickedHandler<Control, MouseEventArgs> Clicked;

    protected void OnButtonClicked(Control sender,MouseEventArgs e) { 
        if (Clicked != null){
            Clicked(sender, e);
        }
    }
}

public class Test {
    public static void main(string[] args)
    {
        StateMachine m = new StateMachine();
        m.Clicked += new MouseDevice.ButtonClickedHandler<Control, MouseEventArgs>(m_Clicked);
    }

    static void m_Clicked(Control sender, MouseEventArgs e)
    {
        //Handle Click Event...
    }
}

Upvotes: 2

Related Questions