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



Advertisements

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

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s

%d bloggers like this: