有人知道如何在WPF中的拖放操作期间获取正确的鼠标位置吗?我尝试使用Mouse.GetPosition()
,但返回的值不正确。
有人知道如何在WPF中的拖放操作期间获取正确的鼠标位置吗?我尝试使用Mouse.GetPosition()
,但返回的值不正确。
没关系,我已经找到了解决方案。使用DragEventArgs.GetPosition()
可以返回正确的位置。
DragOver处理程序是一种通用解决方案。但是,如果您需要在光标不在可放置表面的情况下获取精确的光标位置,则可以使用下面的GetCurrentCursorPosition方法。我参考了Jignesh Beladiya的帖子。
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));
}
}
AllowDrop = false
的部件时,我没有收到DragOver
事件,而这是唯一能给我DragEventArgs
的事件。 - Rico-E