#670 – Getting the Mouse Position Relative to a Specific Element

When you use the Mouse.GetPosition method or MouseButtonEventsArgs.GetPosition method to get the mouse position, you specify that you want the mouse position relative to a particular element.

If you pass a null value into the GetPosition method, you indicate that you want the mouse position relative to the containing window.    However, you can also pass a reference to a control that implements the IInputElement interface.  Since UIElement implements IInputElement, you can pass in a reference to any user interface element.

In the example below, on mouse movement, we display the coordinates of the mouse position relative to the main window, as well as relative to a Button.

        private void win1_MouseMove_1(object sender, MouseEventArgs e)
        {
            Point p = e.GetPosition(null);
            MousePosText = string.Format("GetPosition(null): X = {0}, Y = {1}", p.X, p.Y);

            p = e.GetPosition(btn1);
            MousePosText2 = string.Format("GetPosition(btn1): X = {0}, Y = {1}", p.X, p.Y);
        }



About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #670 – Getting the Mouse Position Relative to a Specific Element

  1. Kumaran.M says:

    Nice explanation

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: