rosst
rosst

Reputation: 177

WPF Mouse Position not retrieved properly

Disclosure: This is my first WPF app. Please be accepting of my ignorance.

In my WPF application, I have a ControlTemplate with a Grid and various children beneath that. In the code-behind, I am dynamically adding a custom ContentControl element using the ControlTemplate.

When the new Control is created, it is intended to capture the mouse and allow dragging capabilities. The code for the dragging calculations is fine if the Grid has already been loaded on the window and I have the start Point set to MouseButtonEventArgs.GetPosition(window). But when the event is fired when the Grid is initially loaded, the Point is equal to the inverse position of the window. E.g. if my window is at (350,250), my start Point is (-350,-250).

private void GridLoaded(object sender, EventArgs e) { // fires MouseLeftButtonDown event for grid}

private void MouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
    ...
    m_start = e.GetPosition(this); // 'this' is the current window; returns the inverse coordinates of 'this'
    ...
}

Is there a more appropriate method to get the x,y coordinates of my mouse position. I could work with screen coordinates if necessary, but all code I've found uses what would be PointToScreen(m_start). This is useless as m_start is incorrect.

Any help is greatly appreciated.

Upvotes: 1

Views: 1055

Answers (1)

Athena Widget
Athena Widget

Reputation: 211

Can you try, I snagged this some time ago and it worked well for me:

    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int X;
        public int Y;

        public static implicit operator Point(POINT point)
        {
            return new Point(point.X, point.Y);
        }
    }

    [DllImport("user32.dll")]
    public static extern bool GetCursorPos(out POINT lpPoint);

    public static Point GetCursorPosition()
    {
        POINT lpPoint;
        GetCursorPos(out lpPoint);
        //bool success = User32.GetCursorPos(out lpPoint);
        // if (!success)

        return lpPoint;
    }

Upvotes: 1

Related Questions