To do this, you need to sample the state of the mouse regularly, and when it's clicked, check the coordinates against the button and see how that goes.
Usually, I write something like this in Button:
public void Update() { // called every tick
var mouseState = Mouse.GetState();
if (this.OnClick != null && mouseState.LeftButton == ButtonState.Pressed && oldState.LeftButton == ButtonState.Released) {
// Someone's listening, and we have a click
this.OnClick.Invoke();
}
this.oldState = mouseState;
}
The core is really:
- Check the mouse state now
- Compare to the old state last tick. If we weren't pressed, and now we are, that's a click.
- Check if anyone's subscribing to our event (
this.OnClick != null), and if so, notify them of the click.
By the way, your event can use Action if you pass no parameters to the subscribers of the click event (C# Forms defaults is to use sender and event args); Action can take parameters if you do want to send some data over.
Eg. you can make your event public event Action OnClick.