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.
18
votes
2 Answers
31
votes
1
votes
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));
}
}