在拖放过程中获取鼠标位置

19

有人知道如何在WPF中的拖放操作期间获取正确的鼠标位置吗?我尝试使用Mouse.GetPosition(),但返回的值不正确。

2个回答

33

没关系,我已经找到了解决方案。使用DragEventArgs.GetPosition()可以返回正确的位置。


4
嗨@J W,GetPosition()的参数是IInputElement。你传递了什么给这个函数? - AFgone
3
我使用了DragEventArgs.GetPosition(this)或者事件绑定的实例来完成操作,结果符合预期。 - beta
1
抱歉挖出这个老帖子,但是:当我拖动那些 AllowDrop = false 的部件时,我没有收到 DragOver 事件,而这是唯一能给我 DragEventArgs的事件。 - Rico-E

2

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));
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接