Mouse Input

Mouse input is done similarly to free text input. The Window object contains various OnXXX events related to the mouse that get called when you do certain things with the mouse. Below is a small list of common events:

  • OnMouseDown: This event is triggered once when a new button is pressed.

  • OnMousePress: This event is triggered while at least one button is being held down.

  • OnMouseUp: This event is triggered once when a button is released.

  • OnMouseWheel: This event is triggered when the user scrolls with their mouse wheel.

  • OnMouseMoving: This event is triggered while the mouse is moving around inside the window.

All these events are only caught as long as the mouse is inside the window area. There may be cases when you would like to keep listening to these events. For instance, when you're dragging a scrollbar, you can typically go outside the window and keep scrolling. To allow this, you can use Input.CaptureMouse(), will allow events to keep being called even when your mouse is not inside the window. To disable this, call Input.ReleaseMouse().

All mouse events take a MouseEventArgs object as their parameter. This method stores a few interesting properties:

  • X: The X position of the mouse relative to the window.

  • Y: The Y position of the mouse relative to the window.

  • LeftButton: Whether the left mouse button is currently held down.

  • OldLeftButton: Whether the left mouse button was held down during the previous input update call.

  • RightButton: Whether the right mouse button is currently held down.

  • OldRightButton: Whether the right mouse button was held down during the previous input update call.

  • MiddleButton: Whether the middle mouse button is currently held down.

  • OldMiddleButton: Whether the middle mouse button was held down during the previous input update call.

  • WheelY: The current value of the mouse scroll. For scrolling just once, this is 1 for scrolling up, and -1 for scrolling down. If the mouse is scrolling very rapidly, these numbers may be higher than 1 or lower than -1.

There are also a few small utility methods:

  • InArea(Rect Rectangle) : Returns whether or not the mouse is currently inside the specified rectangle.

  • Over(Sprite Sprite): Returns whether or not the mouse is currently inside the specified sprite. Must have a bitmap to work.

If you would like to recalculate something based on the mouse's last position but are not inside a mouse event (e.g. in an update event), you can reference Graphics.LastMouseEvent, which will be set to the last mouse event that was fired.

Below you'll find an example of various mouse events in action.

Last updated