XNA - Trapping the Mouse in Windowed Mode

Started by
4 comments, last by BenjaminSergent 12 years, 2 months ago
I'm using XNA to make a game in which mouse movement controls the rotation of the camera. When running in windowed mode, I wanted to ensure that the cursor doesn't leave the screen if the game's not paused. I tried using Mouse.SetPosition, but the mouse still leaves the screen when moved quickly. This semi-frequently results in clicking off the screen, losing focus at undesirable times.
What can I do to prevent this?
Advertisement
Perhaps you can set the mouse window handle property to the graphics device viewport.

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.mouse.windowhandle.aspx
http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.graphicsdevice.viewport.aspx

Because at the moment it would be set to the O.S underlying window.

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.window.aspx
I am going to say this is a VERY VERY idea. The reason people run things in window mode is so we can quickly do other things and then come back to the game. The "correct" way to handle this is to pause your game when the person leaves the area or is in another window.
To imagine the camera controls, think of Minecraft, Skyrim or Counter-Strike. Those games all trap the mouse because they would be unplayable in windowed mode otherwise; in fact, such games can be unplayable full screen with dual monitors if they don't trap the mouse. The player would still be able to quickly switch out by tapping TAB, Alt-TAB or ESC (opening the menu, removing focus from the game window or pausing the game).

blackbook: Unless I'm doing this wrong, changing the window handle doesn't seem to trap the mouse in that window.
I don't know if .Net has an equivalent yet, but in Win32 you can use ClipCursor. I seem to recall having trouble P/invoking it, so I wrote a C++/CLI DLL just for it...
Perfect, that does exactally what I want. For anyone who's curious:



//<Mouse handler class>
[DllImport("user32.dll")]
static extern bool ClipCursor(ref System.Drawing.Rectangle lpRect);

//<In the relevant method>
Mouse.SetPosition( gameWindow.ClientBounds.Width/2,
gameWindow.ClientBounds.Height/2);


System.Drawing.Rectangle window = new System.Drawing.Rectangle( gameWindow.ClientBounds.Left,
gameWindow.ClientBounds.Top,
gameWindow.ClientBounds.Right,
gameWindow.ClientBounds.Bottom );

ClipCursor( ref window );




Obviously, this code only runs when the player is using the mouse for the camera. The mouse is unclipped with no position reseting in every other input state. Thanks for the help.

This topic is closed to new replies.

Advertisement