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.
Asked
Active
Viewed 1.4k times
18

Glorfindel
- 21,988
- 13
- 81
- 109

J W
- 1,679
- 4
- 20
- 28
2 Answers
33
Never mind, I've found a solution. Using DragEventArgs.GetPosition()
returns the correct position.

J W
- 1,679
- 4
- 20
- 28
-
4Hi @J W GetPosition() takes IInputElement as parameter. What did you pass to this function? – AFgone May 21 '12 at 15:55
-
3@AFgone: I did it with DragEventArgs.GetPosition(this) or otherwise just the instance of whatever the event was bound to. Turned out to work as expected. – beta Jul 15 '13 at 11:58
-
1sorry for resurrecting this old thread, but: when I'm dragging over parts that are `AllowDrop = false`, then I don't get the `DragOver `-Event which is the only one to give me `DragEventArgs` – Rico-E Dec 02 '15 at 15:35
1
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));
}
}

Wisebee
- 390
- 2
- 10