好的,所以我之前的问题没有产生任何有用的答案,所以我会尝试从不同的方向来。
我的应用程序可能有几个窗口。给定屏幕坐标中的一个点,我需要找到它“落在”哪个窗口上——即找到包含该点的所有窗口中最重要的窗口。
如果它们Visual
在一个窗口内,我会使用VisualTreeHelper.HitTest
. 但由于它们是不同的窗口,因此不清楚该方法的第一个参数是什么。
这使用纯 WPF 是不可能的,因为 WPF 不公开其窗口的 Z 顺序。事实上,WPF 努力保持一种错觉,即窗口从不会真正相互遮挡。
如果您愿意进行 Win32 调用,解决方案很简单:
public Window FindWindowAt(Point screenPoint) // WPF units (96dpi), not device units
{
return (
from win in SortWindowsTopToBottom(Application.Current.Windows.OfType<Window>())
where new Rect(win.Left, win.Top, win.Width, win.Height).Contains(screenPoint)
select win
).FirstOrDefault();
}
public static IEnumerable<Window> SortWindowsTopToBottom(IEnumerable<Window> unsorted)
{
var byHandle = unsorted.ToDictionary(win =>
((HwndSource)PresentationSource.FromVisual(win)).Handle);
for(IntPtr hWnd = GetTopWindow(IntPtr.Zero); hWnd!=IntPtr.Zero; hWnd = GetWindow(hWnd, GW_HWNDNEXT))
if(byHandle.ContainsKey(hWnd))
yield return byHandle[hWnd];
}
const uint GW_HWNDNEXT = 2;
[DllImport("User32")] static extern IntPtr GetTopWindow(IntPtr hWnd);
[DllImport("User32")] static extern IntPtr GetWindow(IntPtr hWnd, uint wCmd);
如果您的窗口可能是透明的,您还应该在 FindWindowAt() 的“where”子句中使用 VisualTreeHelper.HitTest。