XNA – Displaying Cursor

XNA doesn’t automatically show a mouse pointer within the game window. First, you need a position for your mouse. You’ll also need a 2d texture to display as your mouse pointer
It’s very simple, just load a png image, and displaying it using spriteBatch.Draw();
Of course, we always keep track the mouse position =]

Here’s the code :
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
namespace MouseDisplay
{
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D m_mouseTexture;
Vector2 m_mousePos;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
m_mousePos = Vector2.Zero;
// load the image
m_mouseTexture = Content.Load<Texture2D>("cur");
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
}
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// where is the mouse position now ???
MouseState mouseState = Mouse.GetState();
m_mousePos.X = mouseState.X;
m_mousePos.Y = mouseState.Y;
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
// draw cursor
spriteBatch.Draw(m_mouseTexture, m_mousePos, null, Color.White, 0f,
Vector2.Zero, 1.0f, SpriteEffects.None, 0f);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
Download complete C# Project :
http://www.ziddu.com/download/5519009/MouseDisplay.zip.html
Categories: C#, Programming, XNA
Game, Programming, XNA







SocialVibe