#668 – Retrieving the Mouse’s Current Position

You can retrieve the current position of the mouse at any time using the Mouse.GetPosition method.  Mouse is a static class that provides information about the mouse through a variety of static methods.

The GetPosition method returns a Point object, which contains the and Y position of the mouse, relative to a specified user interface element.

In the example below, we call the GetPosition method and then set a property to report the mouse’s position.  (We’ll bind a label’s Content to this property).  Passing null to GetPosition means that we want the position relative to the top-level window.

        private void win1_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        {
            ReportMousePosition();
        }

        // Can be called at any time (not just from event handler)
        public void ReportMousePosition()
        {
            Point p = Mouse.GetPosition(null);

            MousePosText = string.Format("X = {0}, Y = {1}", p.X, p.Y);
        }



About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #668 – Retrieving the Mouse’s Current Position

  1. Pingback: Dew Drop – October 15, 2012 (#1,422) | Alvin Ashcraft's Morning Dew

  2. Pingback: #670 – Getting the Mouse Position Relative to a Specific Element « 2,000 Things You Should Know About WPF

Leave a comment