Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
This example demonstrates how to get the current horizontal and vertical position of the mouse cursor relative to the upper-left corner a game window.
Note
This example applies only to Windows development. The Mouse and MouseState objects are not supported on Xbox 360.
The example queries the Mouse class to return a MouseState object that holds the button states and the current position of the mouse relative to the upper-left corner of the game window.
To retrieve the current mouse position
- Call GetState to get the current state of the mouse in a MouseState object.
- Access the X and Y properties of the MouseState retrieved in the previous section to get the X (horizontal) and Y (vertical) mouse position, in pixels, relative to the upper-left corner of the game window.
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
#endregion
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
ContentManager content;
int mouseX, mouseY;
public Game1()
{
graphics = new GraphicsDeviceManager( this );
content = new ContentManager( Services );
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadGraphicsContent( bool loadAllContent )
{
if (loadAllContent)
{
}
}
protected override void UnloadGraphicsContent( bool unloadAllContent )
{
if (unloadAllContent == true)
{
content.Unload();
}
}
protected override void Update( GameTime gameTime )
{
// Allows the default game to exit on Xbox 360 and Windows
if (GamePad.GetState( PlayerIndex.One ).Buttons.Back == ButtonState.Pressed)
this.Exit();
// Update our mouse.
UpdateMouse();
base.Update( gameTime );
}
protected void UpdateMouse()
{
MouseState current_mouse = Mouse.GetState();
// The mouse x and y positions are returned relative to the
// upper-left corner of the game window.
mouseX = current_mouse.X;
mouseY = current_mouse.Y;
}
protected override void Draw( GameTime gameTime )
{
graphics.GraphicsDevice.Clear( Color.CornflowerBlue );
base.Draw( gameTime );
}
}