关于c#:MonitorFromWindow(DefaultToNearest)在拖动过程中不起作用

MonitorFromWindow(DefaultToNearest) doesn't work during drag

我正在使用Windows API方法MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST)作为WPF应用程序中某些已覆盖的最大化功能的一部分。我们遇到的一个问题是在拖动操作期间," nearest "窗口没有更新(由Window实例上的DragMove触发)。

假设您在分辨率不同的两个屏幕之间拖动窗口,并在第二个屏幕上触发Aero Snap功能。这将触发有关窗口大小(消息WM_GETMINMAXINFO)的查询。在这种情况下使用MonitorFromWindow返回错误的屏幕。好像MONITOR_DEFAULTTONEAREST所使用的数据直到拖动操作完成才更新,并且直到Aero Snap触发的调整大小功能完成才更新。在回答WM_GETMINMAXINFO查询之前,有什么方法可以刷新当前窗口的位置吗?


由于捕捉是基于鼠标位置的,因此解决此问题的方法是使用GetCursorPos获取当前鼠标位置。然后将该点传递到MonitorFromPoint,以获取当前包含鼠标指针的监视器的句柄。

一个简单的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[DllImport("User32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetCursorPos(ref Point lpPoint);

public const int MONITOR_DEFAULTTONEAREST = 2;

[DllImport("User32.dll")]
public static extern IntPtr MonitorFromPoint(Point pt, UInt32 dwFlags);

public IntPtr GetCurrentMonitor()
{
    Point p = new Point(0,0);
    if (!GetCursorPos(ref p))
    {
        // Decide what to do here.
    }
    IntPtr hMonitor = MonitorFromPoint(p, MONITOR_DEFAULTTONEAREST);
    // validate hMonitor
    return hMonitor;
}