I am developing an XNA game. I run it in window mode.

I need to handle mouse events, but when I use the Mouse class from Xna.Framework.Input.Mouse, I get the the mouse position on the whole screen.

I use this code:

MouseState state = Mouse.getState();
Point position   = new Point(state.X,state.Y);

Rectangle hitbox = new Rectangle(180, 410, 14, 14);

if (area.Contains(mousePosition))
    //fire event

How do I detect the mouse position within the current game window?

  • \$\begingroup\$ Why do you need to get the position of the window? Most of the time you are only interested in the mouse position relative to the top-left of the game window, so I don't see why there's a problem. \$\endgroup\$ – congusbongus Feb 21 '14 at 0:21
  • \$\begingroup\$ By saying "position of the current Window"... i mean the game window.. sorry! \$\endgroup\$ – Leviathan Feb 21 '14 at 10:17
  • \$\begingroup\$ Can you post a picture demonstrating your issue. Also if you are using the debugger Mouse.getState() is updated even when the application is stopped. \$\endgroup\$ – ClassicThunder Oct 21 '14 at 20:44

Mouse should default to reporting its position relative to the game window, but can be configured by assigning the appropriate window handle to Mouse.WindowHandle.

The documentation is here.

  • \$\begingroup\$ i called this assignment in my initialize method, but it changed nothing .. Mouse.WindowHandle = Window.Handle; Where is my mistake? \$\endgroup\$ – Leviathan Feb 21 '14 at 11:01
  • \$\begingroup\$ "Is there a way to detect the mouse position of the current Game Window" is unclear, so I don't really know what you are experiencing. When the mouse is over the top-left corner of the window are you getting a mouse position other than (0,0)? \$\endgroup\$ – Kelly Thomas Feb 22 '14 at 0:49
  • \$\begingroup\$ Yes, when my mouse is on the top left corner of the game window my mouse coordinates are (371,111). \$\endgroup\$ – Leviathan Feb 22 '14 at 9:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.