Partager via


Getting the Mouse Position (Windows, Windows Phone)

Note

This topic applies only to Windows and Windows Phone development. The Mouse and MouseState objects are not supported on Xbox 360.

On Windows, you can use Mouse.GetState at any time to get the mouse position and the state of the mouse buttons.

On Windows Phone, you can also get the primary touch location by using GetState, but only when MouseState.LeftButton is in the Pressed state. The locations in MouseState.X and MouseState.Y will then correspond to the primary touch location on the screen. When LeftButton is in the Released state, X and Y are invalid.

Note

This technique only retrieves the location of the primary touchpoint on a multitouch screen. If you want to retrieve the locations of more than one touchpoint, you should use the technique described in Working with Touch Input (Windows Phone).

To retrieve the current mouse position on Windows

  1. Call Mouse.GetState to get the MouseState object.

  2. Read MouseState.X and MouseState.Y to get the mouse position, in pixels, relative to the upper-left corner of the game window.

To retrieve the primary touch location on Windows Phone

  1. Call Mouse.GetState to get the MouseState object.

  2. If LeftButton is in the Pressed state, read MouseState.X and MouseState.Y to get the screen coordinates of the primary touch location.

Example

The following code demonstrates this procedure:

            MouseState ms = Mouse.GetState();

            if (gameIsPaused)
            {
                if(pausedImageOnScreen && (ms.LeftButton == ButtonState.Pressed))
                {
                    gameIsPaused = false;
                }
                base.Update(gameTime);
                return;
            }

            // on Windows, the current state of the mouse cursor can be obtained at any time.
#if WINDOWS
            curMousePos.X = ms.X;
            curMousePos.Y = ms.Y;
#endif

            // if the mouse button is held down (or the touchscreen is pressed for phone), drop
            // a piece of food at the location given.
            if (canDrop && ms.LeftButton == ButtonState.Pressed)
            {
                foodLocations.Add(new Vector2(ms.X, ms.Y));
                canDrop = false;
            }
            else if (ms.LeftButton == ButtonState.Released)
            {
                // wait until the button is released before allowing the player to drop another
                // piece of food.
                canDrop = true;
            }

See Also

ButtonState