Friday, December 19, 2008

How to get the Mouse Position in a Silverlight Application

Silverlight provides several Mouse events that can be used to determine the position of the mouse. These include

  • MouseMove
  • MouseEnter
  • MouseLeave
  • MouseLeftButtonDown
  • MouseLeftButtonUp

Depending on the event that is fired, you have access to either an object of type MouseEventArgs or MouseButtonEventArgs. This object inside your event handler contains the information you need to determine the current mouse position. In the event handler, call the GetPosition method to retrieve the current mouse position. If you pass in an object, you will get the mouse position relative to that object. If you pass in Null, you will get the mouse position relative to the Silverlight plugin on the page.

Here is a quick example of how to do this.

LayoutRoot.MouseMove += new MouseEventHandler(LayoutRoot_MouseMove);



void LayoutRoot_MouseMove(object sender, MouseEventArgs e)
{
Point position = e.GetPosition(null);
}

1 comment:

  1. Hi I'm displaying popup on mouseenter where ever the mouse pointer but this code doesn't work for me Im using SL4 & blend 4,

    ReplyDelete