May 27th, 2009

Using the mouse position to control movement

All Silverlight Examples, Silverlight 2 tutorials, Silverlight C# Tutorials, Silverlight Effects, by Gavin Wignall.

In the below example we take the co-ordinates of the mouse and use that data to control the position of another item. This can be used for sliders, menus, carousels etc;

I have written the code to adapt to the size of the scrollable area, you can see this by clicking on the ‘+’ and ‘-’ buttons. These will add / remove the items inside the scrollable area. If you remove enough items so that the area taken up is less than that of the screen, the items are positioned in the middle.

To carry out this effect I need to keep track of the mouse position, the width of the screen and the width of the Stack panel containing the items. Each of these values need to be updated when ever they are changed.

I then position the movable area based on the following equations;

Where:
a = Mouse X position
b = Width of Screen area
c = Width of area to be moved
if movable area is bigger than screen area:
moveable area X position = (a/b)*(b-c)
if moveable area is smaller than screen area:
moveable area X position = (b-c)/2

This equation is run every time a frame is rendered.

The User Experience bit

It is an important interaction that when working with scrolling content like this, especially when the content is a menu, to make sure that the direction of new content approaches the movement of the mouse.

Get the code

As always you can download the example files here.

Back Top

Responses to “Using the mouse position to control movement”

  1. Nice example.Thanks very much.

  2. What words… super, excellent idea

  3. Hi, Congratulations to the site owner for this marvelous work you’ve done. It has lots of useful and interesting data.

    Siplelefsoige at June 5, 2009 6:28 am
  4. Yes, I understand you. In it something is also thought excellent, agree with you.

  1. Twitter Trackbacks for Using the mouse position to control movement ยป Silverlight Buzz [silverlightbuzz.com] on Topsy.com (,August 28, 2009)

    [...] link is being shared on Twitter right now. @silverlightnews, an influential author, said Using the mouse [...]

Leave a Reply

Back Top