#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);