#668 – Retrieving the Mouse’s Current Position
October 15, 2012 2 Comments
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 X 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); }