#669 – Retrieving the Mouse’s Current Position in an Event Handler

You can use the static Mouse.GetPosition method anywhere in your code to retrieve the current position of your mouse.

You can also access the mouse position through either the MouseButtonEventArgs or MouseEventArgs object passed in to an event handler for any of the mouse-related events.

In the example below, we use the MouseButtonEventArgs.GetPosition and MouseEventArgs.GetPosition methods in the handlers to get the mouse’s position and to update a related label.

        private void win1_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        {
            Point p = e.GetPosition(null);
            MousePosTextLastClick = string.Format("Last click at X = {0}, Y = {1}", p.X, p.Y);
        }

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


Advertisement