Get the mouse position during drag and drop

13,256

Solution 1

Never mind, I've found a solution. Using DragEventArgs.GetPosition() returns the correct position.

Solution 2

DragOver handler is a solution for general situations. But if you need the exact cursor point while the cursor is not in droppable surfaces, you can use the GetCurrentCursorPosition method below. I refered Jignesh Beladiya's post.

using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Media;

public static class CursorHelper
{
    [StructLayout(LayoutKind.Sequential)]
    struct Win32Point
    {
        public Int32 X;
        public Int32 Y;
    };

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool GetCursorPos(ref Win32Point pt);

    public static Point GetCurrentCursorPosition(Visual relativeTo)
    {
        Win32Point w32Mouse = new Win32Point();
        GetCursorPos(ref w32Mouse);
        return relativeTo.PointFromScreen(new Point(w32Mouse.X, w32Mouse.Y));
    }
}
Share:
13,256
J W
Author by

J W

Updated on June 11, 2022

Comments

  • J W
    J W almost 2 years

    Does anyone know how to get the correct mouse position during a drag-and-drop operation in WPF? I've used Mouse.GetPosition() but the returned value is incorrect.